<?php
/**
 * 裁床
 */
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
use app\common\service\User as UserService;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderUser as OrderUserService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderException as OrderExceptionService;
use app\common\service\Stock as StockService;
use app\common\service\Material as MaterialService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\MaterialStockUse as MaterialStockUseService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\Distributing as DistributingService;
use app\common\service\DistributingFeed as DistributingFeedService;
use Endroid\QrCode\QrCode;
use think\Db;
use app\common\service\Cutting as CuttingService;
use app\common\service\OrderMergeCut as OrderMergeCutService;
use app\common\service\CostCheck as CostCheckService;
class Cutting extends Admin
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 裁剪审核列表
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function auditList()
    {
    	$_st = microtime(true)*1000;
    	$factoryKV = getFactoryKV(false);
    	$factoryOutgoKV = getFactoryOutgoKV(null);
    	$systemUserKV = getSystemUserKV(null);
    	$groupKV = getGroupKV(0);
    	$stallsKV = getStallsKV();
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$factorId      = $this->request->param('factory_id/d', 0);
    		$orderStatus    = $this->request->param('order_status/s');
    		$clientOrdernum    = $this->request->param('client_ordernum/s');
    		$sku    = $this->request->param('sku/s');
    		$createDateRange    = $this->request->param('create_date_range/s');
    		$overDateRange    = $this->request->param('over_date_range/s');
    		$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');
            $breakType    = $this->request->param('break_type/s','');

    		$where[] = ['status', 'in', [0, 1]];
    		$where[] = ['caichuang_can_do', '=', 1];
    		$where[] = ['caichuang_audit_status', 'in', [0, 1]];	// 未审核或部分未审
            //订单加一级
            order_level($where,'');
    		if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}

    		if ($orderStatus != '') {
    			switch ($orderStatus){
    				case 1:
    					$where[] = ['caigou_status', '=', 0];
    					break;
    				case 2:
    					$where[] = ['caigou_status', '=', 1];
    					$where[] = ['caichuang_status', '=', 0];
    					break;
    				case 3:
    					$where[] = ['caichuang_status', '=', 1];
    					$where[] = ['chejian_status', '=', 0];
    					break;
    				case 4:
    					$where[] = ['chejian_status', '=', 1];
    					$where[] = ['tail_status', '=', 0];
    					break;
    				case 5:
    					$where[] = ['tail_status', '=', 1];
    					$where[] = ['status', '=', 0];
    					break;
    				case 6:
    					$where[] = ['status', '=', 2];
    					break;
    			}
    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum', '=', $clientOrdernum];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
    		if ($sku != '') {
    			$where[] = ['sku', 'like', "%".$sku."%"];
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($overDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
    			$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($caichuangOverDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
    			$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
    		}
            if ($breakType != '') {
                $where[] = ['break_code_status', '=',$breakType];
                if($breakType !=1){
                    $where[] = ['tail_status', '<>', 1];
                }
            }

            $order = "shipment_time ASC,create_time ASC";
    		$data['count'] = db('order')->where($where)->count('id');
    		$list = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();

    		$skuService = new SkuService();
    		$orderSizeService = new OrderSizeService();
    		$orderMaterialService = new OrderMaterialService();
    		$stockService = new StockService();
    		$materialStockService = new MaterialStockService();
    		$materialStockUseService = new MaterialStockUseService();
    		$distributingFeedService = new DistributingFeedService();
    		$materialStockCuttingService = new MaterialStockCuttingService();
    		$orderMaterialItemService = new OrderMaterialItemService();

    		foreach ($list as $k => $v) {
    			$osList = $orderSizeService->getListByOrderId($v['id']);
    			$list[$k]['osList'] = $osList;
    			$list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
    			$list[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
    			$list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
    			$list[$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
    			$list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
    			$list[$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
    			$list[$k]['skuStock']=$skuService->getSkuStockBySku($v['sku'],$v['factory_id']);
    			$list[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
    			$list[$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
    			$list[$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
    			$list[$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
    			$list[$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');

                //断码
                $list[$k]['break_code']='';
                if($v['tail_status'] !=1){
                    $break_info=db('order_break')->field('size_list')->where([['client_ordernum', '=', $v['client_ordernum']],['sku','=', $v['sku']]])->find();
                    $list[$k]['break_code']=isset($break_info['size_list'])?$break_info['size_list']:'';
                }

    			$omList = $orderMaterialService->getListByOrderIdForCutting($v['id'], ['fabric', 'lining']);
    			$return_notconfirm=0;
    			foreach ($omList as $sk => $sv) {
                    if($sv['return_notconfirm']==1){ //退换待确认的订单
                        $return_notconfirm=1;break;
                    }
    				$omList[$sk]['total_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);

    				// 实际余料使用量
    				$mscInfo = $materialStockCuttingService->getInfoByMaterialId($sv['order_id'], $sv['material_id'], 'length');
    				$omList[$sk]['length'] = arrayGet($mscInfo, 'length', '');
                    $omiList2 = $orderMaterialItemService->material_cloth_plan(0, $sv['order_id']);
                    $omList[$sk]['rejects_length_sum'] = array_sum(array_column($omiList2, 'rejects_length'));
                    $metreLeftInfo = $materialStockService->checkPrivateMetres($sv['material_id'], $sv['order_id']);
                    $omList[$sk]['have_metres'] = $metreLeftInfo['have_metres'];
                    $omList[$sk]['used_metres'] = $metreLeftInfo['used_metres'];

    				// 是否验布缩水都已完成
    				$omList[$sk]['checkcloth_shrink_is_over'] = $orderMaterialItemService->checkCheckclothShrinkOver($sv['order_id'], $sv['material_id'])?1:0;
    			}
    			$list[$k]['omList'] = $omList;
                if($return_notconfirm==1){
                    //$list[$k]['factory_name']='return_notconfirm';
                    $data['count']-=1;unset($list[$k]);
                };
    		}
    		$data['data'] = array_values($list);
    		$data['code'] = 0;
    		$data['msg'] = '';

    		$_et = microtime(true)*1000;
    		$data['time'] = $_et-$_st;

    		return json($data);
    	}

    	$assign = [
    		'factoryKV' => [0 => '请选择'] + $factoryKV,
    		'stallsKV' => $stallsKV,
    		'systemUserKV' => $systemUserKV,
    		'caichuangTypeKV' => config('mimo.caichuang_type'),
    	];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 保存裁床备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function remark() {
    	$mid       = $this->request->param('mid/d', 0);
    	$orderId       = $this->request->param('order_id/d', 0);
    	$remark   = $this->request->param('remark/s', '');
    	$upData = [
    		'caichuang_remark' => $remark,
    		'update_time' => time(),
    	];
    	if ($mid) {
    		$ret = db('order_material')->where('mid', $mid)->update($upData);
    	} else {
    		$ret = db('order')->where('id', $orderId)->update($upData);
    	}
    	$this->addOrderLog($orderId, '', "保存裁床备注[{$remark}]");
    	if ($ret) {
    		return $this->Json(1, '保存备注信息成功');
    	} else return $this->Json(0);
    }

    /**
     * 面料计划框
     *
     * @author King
     * @date 2020年8月27日
     *
     */
    public function plan() {
    	$mid = $this->request->param('mid/d', 0);
        $skuService=new SkuService();
    	$orderService = new OrderService();
    	$orderSizeService = new OrderSizeService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$materialStockCuttingService = new MaterialStockCuttingService();

    	$omInfo = $orderMaterialService->getInfoById($mid);
    	if (empty($omInfo)) {
    		return $this->error('非法访问');
    	}
    	// 更新布号米长
    	$orderMaterialItemService->updateLength($omInfo['order_id'], $omInfo['material_id']);
    	$orderInfo=$orderService->getInfoById($omInfo['order_id']);
        $skuStockList=$skuService->getSkuStockBySku($orderInfo['sku'],$orderInfo['factory_id']);
        $stockSizeIndexList=array_column($skuStockList,'available_count','size_name');
    	$osList = $orderSizeService->getListByOrderId($omInfo['order_id']);
    	$omiList = $orderMaterialItemService->material_cloth_plan($mid);
    	$mscInfo = $materialStockCuttingService->getInfoByMaterialId($omInfo['order_id'], $omInfo['material_id']);
    	$oddments=db('material_stock_use')->where([['material_id', '=', $omInfo['material_id']], ['order_id', '=', $omInfo['order_id']]])->where([['status','in',[1,2]]])->select();

    	$assign = [
    		'mid' => $mid,
    		'oInfo' => $orderInfo,
    		'omInfo' => $omInfo,
    		'osList' => $osList,
    		'omiList' => $omiList,
            'oddments' => $oddments,
    		'mscInfo' => $mscInfo,
            'skuStockList'=>$stockSizeIndexList,
    		'overfeedReasonKV' => config('mimo.overfeed_reason'),
    	];
    	return $this->assign($assign)->fetch();
    }
    /**
     * 面料计划录入
     *
     * @author King
     * @date 2020年8月27日
     *
     */
    public function planSave() {
    	$mid = $this->request->param('mid/d', 0);
		$caichuangFabricWidth = $this->request->param('caichuang_fabric_width/f', 0);
    	$wheatLowCountArr = $this->request->param('wheat_low_count', []);	// 低层码数明细
    	$wheatHeightCountArr = $this->request->param('wheat_height_count', []);	// 高层码数明细

    	$caichuangStripDosage = $this->request->param('caichuang_strip_dosage/f', 0);	// 捆条单件用量
    	$caichuangWheatLowLength = $this->request->param('caichuang_wheat_low_length/f', 0);	// 唛架总米长(低层)
    	$caichuangWheatHeightLength = $this->request->param('caichuang_wheat_height_length/f', 0);	// 唛架总米长(高层)
        $caichuangStripWidth=$this->request->param('caichuang_strip_width/f', 0);//捆条宽度
        $material_per=$this->request->param('material_per/f', 0);//料率百分比
    	$caichuangWheatHeightArr = $this->request->param('caichuang_wheat_height', []);	// 计划拉布层数(高层)
    	$caichuangWheatLowArr = $this->request->param('caichuang_wheat_low', []);	// 计划拉布层数(低层)
		$overfeedReason = $this->request->param('overfeed_reason/d', 0);	// 超量理由
    	$dif1 = $this->request->param('dif1/f', 0);
    	$dif2 = $this->request->param('dif2/f', 0);
    	$mscArr = $this->request->param('msc', []);	// 库存面料
    	$orderService = new OrderService();
    	$orderSizeService = new OrderSizeService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$materialStockCuttingService = new MaterialStockCuttingService();

    	$omInfo = $orderMaterialService->getInfoById($mid);
    	if (empty($omInfo)) {
    		return $this->error('非法访问');
    	}
    	$orderId = $omInfo['order_id'];
    	$clientOrdernum = $omInfo['client_ordernum'];
    	$materialId = $omInfo['material_id'];

    	$osList = $orderSizeService->getListByOrderId($orderId);

    	try {
    		db()->startTrans();

    		// 设置裁床基准物料（客户用量最大的物料）
    		$orderMaterialService->setCaichuangStandard($orderId);
    		// 更新order_size表
    		$caichuangWheatLowNumber = 0;	// 裁床麦架件数(低层)
    		$caichuangWheatHeightNumber = 0;	// 裁床麦架件数(高层)
    		foreach ($osList as $k => $v) {
    			$lowDetail = $v['wheat_low_count_detail'];
    			$heightDetail = $v['wheat_height_count_detail'];
    			$lowDetail[$mid] = arrayGet($wheatLowCountArr, $v['mid'], 0);
    			$heightDetail[$mid] = arrayGet($wheatHeightCountArr, $v['mid'], 0);

    			$caichuangWheatLowNumber += $lowDetail[$mid];
    			$caichuangWheatHeightNumber += $heightDetail[$mid];
    			$upData = [
    				'wheat_low_count_detail' => json_encode($lowDetail),
    				'wheat_height_count_detail' => json_encode($heightDetail),
    				'update_time' => time(),
    			];
    			db('order_size')->where('mid', $v['mid'])->update($upData);
    		}
    		// 更新order_material_item表
    		foreach ($caichuangWheatHeightArr as $k => $v) {
    			$upData = [
    				'caichuang_wheat_low' => arrayGet($caichuangWheatLowArr, $k, 0),
    				'caichuang_wheat_height' => $v,
    				'caichuang_plan_status' => 1,
    				'update_time' => time(),
    			];
    			db('order_material_item')->where('id', $k)->update($upData);
    		}

    		// 更新material_stock_cutting库存面料裁剪记录表
    		$mscData = [];
    		if($mscArr) {
    			foreach ($mscArr as $k => $v) {
    				$mscData = $v;
    				$upData = [
    					'caichuang_wheat_height' => $v['caichuang_wheat_height'],
    					'caichuang_wheat_low' => $v['caichuang_wheat_low'],
    					'caichuang_plan_status' => 1,
    					'update_time' => time(),
    				];
    				db('material_stock_cutting')->where('id', $k)->update($upData);
    			}
    		}

    		$omiList = $orderMaterialItemService->getListByOrderMaterialId($mid);
    		$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $materialId);

    		// 更新order_material表
    		$caichuangStatus = 0;
    		if(array_sum(array_column($omiList, 'caichuang_plan_status')) == count($omiList) && (empty($mscInfo) || !empty($mscInfo) && $mscInfo['caichuang_plan_status']==1)) {
    			$caichuangStatus = 1;
    		}
    		$upData = [
				'caichuang_fabric_width' => $caichuangFabricWidth,
    			'caichuang_strip_dosage' => $caichuangStripDosage,
    			'caichuang_wheat_low_length' => $caichuangWheatLowLength,	// 低层长度
    			'caichuang_t_wheat_low_length' => $caichuangWheatLowLength,	// 实际低层长度
    			'caichuang_wheat_height_length' => $caichuangWheatHeightLength,	// 高层长度
    			'caichuang_t_wheat_height_length' => $caichuangWheatHeightLength,	// 实际高层长度
    			'caichuang_wheat_low_number' => $caichuangWheatLowNumber,	// 低层件数
    			'caichuang_t_wheat_low_number' => $caichuangWheatLowNumber,	// 实际低层件数
    			'caichuang_wheat_height_number' => $caichuangWheatHeightNumber,	// 高层件数
    			'caichuang_t_wheat_height_number' => $caichuangWheatHeightNumber,	// 实际高层件数
                'caichuang_strip_width'=>$caichuangStripWidth,//捆条宽度
                'material_per'=>$material_per,//料率百分比
    			'caichuang_wheat_low' => array_sum(array_column($omiList, 'caichuang_wheat_low')) + arrayGet($mscData, 'caichuang_wheat_low', 0),
    			'caichuang_wheat_height' => array_sum(array_column($omiList, 'caichuang_wheat_height')) + arrayGet($mscData, 'caichuang_wheat_height', 0),
    			'caichuang_strip' => array_sum(array_column($omiList, 'caichuang_strip')) + arrayGet($mscData, 'caichuang_strip', 0),
    			'caichuang_neadend' => array_sum(array_column($omiList, 'caichuang_neadend')) + arrayGet($mscData, 'caichuang_neadend', 0),
    			'caichuang_status' => $caichuangStatus,
    			'update_time' => time(),
    		];
    		// 计算应裁数=高层数*高层件数+低层数*低层件数
    		$yingcaiCount = $upData['caichuang_wheat_low_number'] * $upData['caichuang_wheat_low'] + $upData['caichuang_wheat_height_number'] * $upData['caichuang_wheat_height'];
    		$upData['yingcai_count'] = $yingcaiCount;

    		// 计算裁床实际单件用量=唛架总长度/总件数 + 捆条实际单件用量
    		if($caichuangWheatLowNumber+$caichuangWheatHeightNumber > 0) {
				$low=$caichuangWheatLowNumber!=0?($caichuangWheatLowLength/$caichuangWheatLowNumber):0;
				$hight=$caichuangWheatHeightNumber!=0?($caichuangWheatHeightLength/$caichuangWheatHeightNumber):0;
				$num=2;
				if($low==0 || $hight==0) $num=1;
				$upData['caichuang_shiji_dosage'] = round(($low+$hight)/$num, 2) + $caichuangStripDosage;
    		}
			if(isset($upData['caichuang_shiji_dosage'])) db('order_material')->where('mid', $mid)->update($upData);

			//添加超量表
			if(isset($upData['caichuang_shiji_dosage']) && ($dif1 > 0.03 || $dif2 > 0.05)){
				$overfeedData = [
					'order_id' => $omInfo['order_id'],
					'client_ordernum' => $omInfo['client_ordernum'],
					'order_material_id' => $omInfo['mid'],
					'material_id' => $omInfo['material_id'],
					'factory_id' => $omInfo['factory_id'],
					'customer_dosage' => $omInfo['customer_dosage'],
					'material_dosage' => $upData['caichuang_shiji_dosage'],
					'overfeed_reason' => $overfeedReason,
					'create_time' => time(),
					'update_time' => time(),
				];
				db('overfeed')->insert($overfeedData,true);
                $CostCheckService=new CostCheckService();
                $createret=$CostCheckService->set_cost_check_select_2([$omInfo['order_id']]);//判断并生成【单件用量】核价任务
			}
			$this->addOrderLog($orderId, $clientOrdernum, "面料[{$omInfo['mInfo']['name']}]计划录入".($overfeedReason!=''?"，超量理由：{$overfeedReason}":''));
    		db()->commit();

    		$omInfo = $orderMaterialService->getInfoById($mid);
    		$omInfo['orderId'] = $orderId;
    		return $this->Json(1, '操作成功', $omInfo);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}

    }
	 /**
     * 超量报表
     *
     * @author 飞燕
     * @date 2021年1月26日
     *
     */
    public function overfeed() {
        $materialService=new MaterialService();
		$factoryKV = getFactoryKV(false);
        $cuttingService=new CuttingService();
        $systemUserKV = getSystemUserKV(null);
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where      = $data = [];
            $isAutoImport    = $this->request->param('is_auto_import/s');
			$factorId      = $this->request->param('factory_id/d', 0);
			$createDateRange    = $this->request->param('create_date_range/s');//发起时间筛选
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $overfeed_reason    = $this->request->param('overfeed_reason/s');
            $export     = $this->request->param('export/d', 0);
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $keyword    = $this->request->param('keyword/s');
            if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}

            if ($isAutoImport) {
				$where[] = ['o.is_auto_import', '=', $isAutoImport];
			}
            if ($factorId) {
                    $where[] = ['of.factory_id', '=', $factorId];
            }
			if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['of.create_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($clientOrdernum != '') {
                    $where[] = ['of.client_ordernum', '=', $clientOrdernum];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $where[] = ['of.order_id', '=', $temp['id']];
                    }
                    break;
            }
            //订单加一级
            order_level($where,'o.');
            if ($overfeed_reason) {
                    $where[] = ['overfeed_reason', '=', $overfeed_reason];
            }
			$where[] = ['of.overfeed_show', '=', 0];
			$data['data']=db('overfeed of')->join('order o', "of.order_id=o.id", 'left')->field('of . *,o.create_time as order_time,o.is_auto_import,o.sku,o.caichuang_user_id')->page($page)->limit($limit)->where($where)->select();
			$overfeedReasonKV = config('mimo.overfeed_reason');
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['mInfo'] =$materialService->getInfoById($v['material_id']);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['overfeed_reason_detail'] = arrayGet($overfeedReasonKV, $v['overfeed_reason'], '');
				$data['data'][$k]['is_auto_import_name'] = arrayGet(config('mimo.order_from'), $v['is_auto_import'], '');
            }
            //导出
            if ($export) {
                $this->_overfeedXls('超量报表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['count'] =db('overfeed of')->join('order o', "of.order_id=o.id", 'left')->field('of . *,o.create_time as order_time,o.is_auto_import,o.sku')->where($where)->count('of.id');
            $data['code'] = 0;
            $data['msg'] = '';

            return json($data);
        }
        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
           //'systemUserKV' => $systemUserKV,

        ];
        return $this->assign($assign)->fetch();
	}
	public function overfeedConfirm(){
		$id = $this->request->param('id/d', 0);
		if($id==0)	return $this->Json(0);
		$result=db('overfeed')->where('id',$id)->update(['overfeed_show'=>1]);
		return $this->Json(1);
	}
    /**
     * 裁床审核
     *
     * @author King
     * @date 2020年9月1日
     *
     */
    public function audit() {
    	$mid = $this->request->param('mid/d', 0);
    	$status = $this->request->param('status/d');

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();

    	$omInfo = $orderMaterialService->getInfoById($mid);
    	if (empty($omInfo)) {
    		return $this->error('非法访问');
    	}
    	$orderId = $omInfo['order_id'];
    	$clientOrdernum = $omInfo['client_ordernum'];
    	$materialId = $omInfo['material_id'];

    	try {
    		if (!in_array($status, [2, 3])) {
    			throw new \Exception('参数错误');
    		}

    		db()->startTrans();

    		// 记录状态
    		$upData = [
    			'caichuang_status' => $status,
    			'caichuang_audit_time' => time(),
    			'update_time' => time(),
    		];

    		db('order_material')->where('mid', $mid)->update($upData);

    		// 检测面料是否都已审核
    		$omList = $orderMaterialService->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
    		$overNum = 0;
    		foreach ($omList as $v) {
    			if ($v['caichuang_status'] == 3) $overNum++;
    		}
    		$caichuangAuditStatus = ($overNum == count($omList)) ? 2 : ($overNum > 0 ? 1: 0);

    		// 标记订单裁床审核状态（0未审核，1已部分审核，2已全部审核）
    		db('order')->where('id', $orderId)->update(['caichuang_audit_status' => $caichuangAuditStatus, 'update_time' => time()]);

    		$this->addOrderLog($orderId, $clientOrdernum, "面料[{$omInfo['mInfo']['name']}]计划审核".($status==2?'不通过':'通过'));
    		db()->commit();

    		return $this->Json(1, '操作成功', ['isAllOver' => $caichuangAuditStatus, 'mid' => $mid, 'status' => $status, 'orderId' => $orderId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 回退到采购环节
     */
    public function back()
    {
    	$orderId = $this->request->param('order_id/d', 0);

    	try {
    		db()->startTrans();

	    	// 删除 wx_order_user 记录
	    	db('order_user')->where('order_id', $orderId)->delete();

	    	// 重置 wx_order_material 数据
	    	$data = [
	    		'caigou_status' => 0,
	    		'caigou_over_time' => 0,
	    		'caichuang_fabric_width' => 0,
	    		'caichuang_adaption' => 0,
	    		'caichuang_neadend' => 0,
	    		'caichuang_strip' => 0,
	    		'caichuang_defect' => 0,
	    		'caichuang_dosage' => 0,
	    		'caichuang_bsp_length' => 0,
	    		'caichuang_wheat_low_length' => 0,
				'caichuang_wheat_low_number' => 0,
				'caichuang_wheat_low' => 0,
				'caichuang_wheat_height_length' => 0,
				'caichuang_wheat_height_number' => 0,
				'caichuang_wheat_height' => 0,
				'caichuang_wheat_per_loss' => 0,
				'caichuang_t_adaption' => 0,
				'caichuang_t_neadend' => 0,
				'caichuang_t_strip' => 0,
				'caichuang_t_defect' => 0,
				'caichuang_t_wheat_low_length' => 0,
				'caichuang_t_wheat_low_number' => 0,
				'caichuang_t_wheat_low' => 0,
				'caichuang_t_wheat_height_length' => 0,
				'caichuang_t_wheat_height_number' => 0,
				'caichuang_t_wheat_height' => 0,
				'caichuang_layers' => 0,
	    		'caichuang_status' => 0,
	    		'caichuang_over_time' => 0

	    	];
	    	db('order_material')->where('order_id', $orderId)->update($data);

	    	// 重置 wx_order 数据
	    	$data = [
	    		'caigou_status' => 0,
	    		'caigou_over_time' => 0,
	    		'caichuang_can_do' => 0,
	    		'caichuang_can_do_time' => 0,
	    		'caichuang_status' => 0,
	    		'caichuang_user_id' => 0,
	    		'caichuang_over_time' => 0,
	    		'caichuang_remark' => '',
	    		'caichuang_chuanghao' => 0,
	    		'caichuang_park_dosage' => 0
	    	];
	    	db('order')->where('id', $orderId)->update($data);

	    	$this->addOrderLog($orderId, '', '回退到采购环节');
	    	db()->commit();

	    	return $this->Json(1, '操作成功');
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 裁剪任务
     *
     * @author KING
     * @date 2020年7月17日
     *
     */
    public function task() {
    	$mid = $this->request->param('mid/d', 0);
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');

    	$error = '';
    	$oInfo = [];
    	$sInfo = [];
    	$osList = [];
    	$omList = [];
        $csList = [];
		$omcInfo = [];
		$ouList = [];
		$clientOrdernumArr=[];$zhahaos=[1,2,3,4,5,6,7];$is_cut_merge='1';
    	if ($clientOrdernum != '') {
    		$orderService = new OrderService();
    		$skuService = new SkuService();
    		$orderSizeService = new OrderSizeService();
    		$orderMaterialService = new OrderMaterialService();
    		$orderMaterialItemService = new OrderMaterialItemService();
    		$materialStockCuttingService = new MaterialStockCuttingService();
                $checkClothShrinkService = new \app\common\service\CheckclothShrink();

    		$oInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    		if (!$oInfo) {
    			$error = "未找到订单信息";
    		} elseif($oInfo && $oInfo['caichuang_audit_status']==0 && $oInfo['caichuang_status'] == 0) {
    			$error = "该订单还未进行裁剪审核";
			} else {
    			$orderId = $oInfo['id'];
    			$clientOrdernum = $oInfo['client_ordernum'];
				$where=[
					['client_ordernum','like',"%".$clientOrdernum."%"],
				];
				$omcInfo=db('order_merge_cut')->where($where)->findOrEmpty();
				if($omcInfo){
					$clientOrdernumArr= explode(',', $omcInfo['client_ordernum']);
					$zhahaos=db('order_user')->where([['client_ordernum','in',$clientOrdernumArr]])->order('client_ordernum asc,zhahao asc')->group("zhahao")->column("zhahao");
					$ouList1=db('order_user')->where([['client_ordernum','in',$clientOrdernumArr]])->order('client_ordernum asc,zhahao asc')->select();
					$caichaungRemarkKV=db('order')->where([['client_ordernum','in',$clientOrdernumArr],['status','not in',99]])->column("id,caichuang_remark");

					foreach ($ouList1 as $key => $value) {
						if($value['fei_status']==1) $value['jinpeng_status']=4;
						$ouList[$value['order_id']][0][$key]=$value;
						$ouList[$value['order_id']][1] = arrayGet($caichaungRemarkKV, $value['order_id'],'');
					}
				}else{
                    $is_cut_merge=0;
                    $clientOrdernumArr=[$orderId=>$clientOrdernum];
                    $zhahaos=db('order_user')->where([['order_id','in',$orderId]])->order('client_ordernum asc,zhahao asc')->group("zhahao")->column("zhahao");
					$sInfo = $skuService->getInfoBySku($oInfo['sku']);
					$osList = $orderSizeService->getListByOrderId($orderId);
					$csList = $checkClothShrinkService->getInfoByOrderId($orderId);
					$omList = $orderMaterialService->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
					foreach ($omList as $k => $omInfo) {
						$materialId = $omInfo['material_id'];
						$omList[$k]['omiList'] = $orderMaterialItemService->getListByOrderMaterialId($omInfo['mid']);
						$omList[$k]['mscInfo'] = $materialStockCuttingService->getInfoByMaterialId($orderId, $materialId);
						$omList[$k]['material_stock_id']=db('material_stock')->where([['order_id','=',$orderId],['material_id','=',$materialId]])->value("id",'');
					}
				}
    		}
    	}
        $storehouseKV = getStorehouseKV();
        $storeshelfMap = [];
        foreach ($storehouseKV as $k => $v) {
            if ($k > 0)	$storeshelfMap[$k] = getStoreshelfKV($k);
        }
        $storeHouse=['' => '请选择'] + $storehouseKV;
    	$assign = [
			'jinpengStatusKV'=>[0=>'<span class="blue">未同步</span>',1=>'已同步',2=>'<span class="red">同步失败</span>',3=>'同步删除',4=>'<span class="green">已开货</span>'],
    		'clientOrdernum' => $clientOrdernum,
            'orderNumberArr'=>$clientOrdernumArr,
            'is_cut_merge'=>$is_cut_merge,
			'omcInfo'=>$omcInfo,
			'ouList'=>$ouList,
    		'error' => $error,
    		'oInfo' => $oInfo,
    		'sInfo' => $sInfo,
    		'osList' => $osList,
            'csList'=>$csList,
    		'omList' => $omList,
            'storeHouse'=>$storeHouse,
    		'mid' => $mid,	// 展开的卡片订单物料mid
    	];

        $packeg_remark=["前","后","左","右","上","下","袖子","口袋","腰","脚"];
        foreach ($zhahaos as $key => $value) {
            $auditUser=$otherUser=['name'=>$value,'value'=>$value];
            $auditUser['selected']=true;
            $assign['cut_zhahaos'][]=$auditUser;
        }
        $assign['cut_zhahaos']=empty($zhahaos) ? [] :$assign['cut_zhahaos'];
        foreach ($packeg_remark as $key => $value) {
            $auditUser=['name'=>$value,'value'=>$value];
            if($key<8)$auditUser['selected']=true;
            $assign['packeg_remark'][]=$auditUser;
        }
        $assign['storeshelfMap'] = $storeshelfMap;
    	return $this->assign($assign)->fetch();
    }

	/*
	* 扎数编辑
	*/
    public function stripEdit() {
        $orderId = $this->request->param('order_id/d', 0);
        $orderService = new OrderService();
        $skuService = new SkuService();
        $orderSizeService = new OrderSizeService();
        $orderMaterialService = new OrderMaterialService();
        $orderUserService = new OrderUserService();

        $orderInfo = $orderService->getInfoById($orderId);
        if (empty($orderInfo)) return $this->error('订单不存在');

        $skuInfo = $skuService->getInfoBySku($orderInfo['sku']);
        $orderSize = $orderSizeService->getListByOrderId($orderId);
        $orderMaterial = $orderMaterialService->getListByOrderId($orderId);
        $orderUser = $orderUserService->getListByOrderId($orderId);
		foreach ($orderUser as $kou => $vou) {
			if($vou['fei_status']==1) $orderUser[$kou]['jinpeng_status']=4;
		}
        $groupKV = getGroupKV($orderInfo['factory_id']);

        if ($this->request->isAjax()) {
			try {
				db()->startTrans();
				// 订单详细
				$post = $this->request->param();

				// 裁床数据
				$zhahao = arrayGet($post, 'zhahao', []);
				$jianshu = arrayGet($post, 'jianshu', []);
				$sizeName = arrayGet($post, 'size_name', []);
				$chuanghao = arrayGet($post, 'chuanghao', []);
				$orderUserOriMap = db('order_user')->where('order_id', $orderId)->column('jinpeng_status,jinpeng_qty,jinpeng_size_name,jinpeng_chuanghao,mid,chuanghao,size_name,jianshu,create_time', 'zhahao');
				$zhahaoJinpeng = db('order_user')->where('order_id', $orderId)->where('jinpeng_status', 1)->column('zhahao'); // 金鹏已同步的扎号
				//删除扎数
				$zhahaoOri = array_keys($orderUserOriMap);
				$zhahaoDel = [];
				$zhahaoDel = array_diff($zhahaoOri, $zhahao);
				$zhahaoAdd = array_diff($zhahao ,$zhahaoOri);//dump($zhahaoAdd);dump($post);exit();
				$zhahaoJinpengDel = array_intersect($zhahaoDel, $zhahaoJinpeng); // 金鹏需删除的扎号
				if(!empty($zhahaoDel)){
					db('order_user')->where("order_id", $orderId)->where('zhahao', 'in', $zhahaoDel)->delete();
				}
				foreach ($zhahao as $key => $val) {
					$orderUserData = [
						'zhahao' => $val,
						'jianshu' => $jianshu[$key],
						'size_name' => $sizeName[$key],
						'chuanghao' => $chuanghao[$key],
						'update_time' => time(),
					];

					// 处理金鹏系统对应的字段信息start
					$orderUserData['jinpeng_status'] = 0;
					if (isset($orderUserOriMap[$val]) && $orderUserOriMap[$val]['jinpeng_status'] == 1) {
						$zhaInfo = $orderUserOriMap[$val];
						if($zhaInfo['jinpeng_chuanghao'] == $orderUserData['chuanghao'] && $zhaInfo['jinpeng_qty'] == $orderUserData['jianshu'] && $zhaInfo['jinpeng_size_name'] == $orderUserData['size_name']) $orderUserData['jinpeng_status'] = 1;
					}
					// 处理金鹏系统对应的字段信息end

					$info = db('order_user')->where("order_id = {$orderId} and zhahao = {$val}")->findOrEmpty();
					if ($info) {
						db('order_user')->where('mid', $info['mid'])->update($orderUserData);
					} else {
						$orderUserData['factory_id'] = $orderInfo['factory_id'];
						$orderUserData['order_id'] = $orderInfo['id'];
						$orderUserData['client_ordernum'] = $orderInfo['client_ordernum'];
						$orderUserData['create_time'] = time();
						db('order_user')->insertGetId($orderUserData);
					}
					$orderSizeArr[$sizeName[$key]][]=$jianshu[$key];
				}
				//同步更新order_size表
                $material_shicai_count=0;
				foreach ($orderSizeArr as $k => $v) {
					$orderUserData = [
						'shicai_count' => array_sum($v),
						'update_time' => time(),
					];
                    $material_shicai_count+=$orderUserData['shicai_count'];
					$where=[
						['order_id','=',$orderId],
						['size_name','=',$k]
					];
					db('order_size')->where($where)->update($orderUserData);
				}
                db('order_material')->where('order_id',$orderId)->update(['shicai_count'=>$material_shicai_count]);

				$jinPengDelData=[];

				$msgTmp = "";
				if($orderInfo['jinpeng_status'] == 1 && isset($zhahaoJinpengDel) && !empty($zhahaoJinpengDel)){
					// 通知金鹏删除扎号
					foreach ($zhahaoJinpengDel as $kd => $vd) {
						$orderUserOriMap[$vd]['jinpeng_status']=4;
						$jinPengDelData[]=$orderUserOriMap[$vd];
					}
					$orderService->syncJinpengCut($orderId,'edit','dele',$jinPengDelData);
					$msgTmp = "，从金鹏删除扎号" .implode(",", $zhahaoJinpengDel);
				}
				if($orderInfo['jinpeng_status'] == 1 && isset($zhahaoAdd) && !empty($zhahaoAdd)){
					// 通知金鹏添加扎号
					foreach ($zhahaoAdd as $ka => $va) {
						$osInfo=db('order_user')->where("order_id=".$orderId." and zhahao=".$va)->findOrEmpty();
						$jinPengAddData[]=$osInfo;
					}
					$orderService->syncJinpengCut($orderId,'edit','edit',$jinPengAddData);
					$msgTmp = "，从金鹏新增扎号".implode(",", $zhahaoAdd);
				}
				$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "编辑保存扎数" . $msgTmp);
				db()->commit();

				return $this->Json(1, '修改成功');
			} catch (\Exception $e) {
				db()->rollback();
				return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
			}
        }

        $assign = [
			'jinpengStatus'=>['0'=>'未同步','1'=>'已同步','2'=>'同步失败','3'=>'同步删除','4'=>'已开货'],
			'orderId' => $orderId,
			'oInfo' => $orderInfo,
			'ouList' => $orderUser,
			'sizeNameArr' => array_unique(array_column($orderSize, 'size_name')),
        ];
        return $this->assign($assign)->fetch();
	}
     /* 重置单个唛架信息
     *
     * @author King
     * @date 2020年9月3日
     *
     */
    public function resetItem() {
    	$mid = $this->request->param('mid/d', 0);

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();

    	$omInfo = $orderMaterialService->getInfoById($mid);
    	if (empty($omInfo)) {
    		return $this->error('非法访问');
    	}
    	$orderId = $omInfo['order_id'];
    	$clientOrdernum = $omInfo['client_ordernum'];
    	$materialId = $omInfo['material_id'];

    	try {
    		db()->startTrans();

    		// 记录状态
    		$upData = [
    			'caichuang_pull_status' => 0,
    			'caichuang_pull_time' => 0,
    			'caichuang_status' => 2,
    			'caichuang_audit_time' => time(),
    			'update_time' => time(),
    		];
    		db('order_material')->where('mid', $mid)->update($upData);
            db('material_stock')->where([['order_id','=',$orderId],['material_id','=',$materialId]])->delete();
    		// 检测面料是否都已审核
    		$omList = $orderMaterialService->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
    		$overNum = 0;
    		foreach ($omList as $v) {
    			if ($v['caichuang_status'] == 3) $overNum++;
    		}
    		$caichuangAuditStatus = ($overNum == count($omList)) ? 2 : ($overNum > 0 ? 1: 0);

    		db('order')->where('id', $orderId)->update(['caichuang_audit_status' => $caichuangAuditStatus, 'update_time' => time()]);
    		//初始化 订单工价-对帐单表 wx_order_progress_price
//            $res3 = (new \app\common\service\ProcessPriceOrder())->cutting_resetItem_del($orderId);
    		$this->addOrderLog($orderId, $clientOrdernum, "面料[{$omInfo['mInfo']['name']}]裁剪唛架信息重置");
    		db()->commit();

    		return $this->Json(1, '操作成功');
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 重置订单所有唛架信息
     *
     * @author King
     * @date 2020年9月3日
     *
     */
    public function resetOrder() {
    	$orderId = $this->request->param('order_id/s', '');

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();

    	$oInfo = $orderService->getInfoById($orderId);
    	if (empty($oInfo)) {
    		return $this->error('非法访问');
    	}

    	$clientOrdernum = $oInfo['client_ordernum'];

    	try {
    		db()->startTrans();

    		$list = $orderMaterialService->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
    		foreach ($list as $v) {
    			$upData = [
    				'caichuang_pull_status' => 0,
    				'caichuang_pull_time' => 0,
    				'caichuang_status' => 2,
    				'caichuang_audit_time' => time(),
    				'update_time' => time(),
    			];
    			db('order_material')->where('mid', $v['mid'])->update($upData);
    		}
    		db('order')->where('id', $orderId)->update(['caichuang_audit_status' => 0, 'update_time' => time()]);
            db('distributing')->where("order_id = {$orderId}")->delete();//清除配料出库单

    		$this->addOrderLog($orderId, $clientOrdernum, "裁剪订单重置");
    		db()->commit();
			if($oInfo['jinpeng_status']==1){
				$orderService->syncJinpengOrder($orderId,'dele');
				$orderService->syncJinpengCut($orderId,'dele');
			}

    		return $this->Json(1, '操作成功');
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 实裁数据录入
     */
    public function realData() {
    	$id = $this->request->param('id/d', 0);
    	$type = $this->request->param('type/d', 0);	// 类型（0条布，1库存面料）

    	$orderMaterialService = new OrderMaterialService();
    	$materialStockCuttingService = new MaterialStockCuttingService();
    	$orderMaterialItemService = new OrderMaterialItemService();

    	if ($type == 1) {
    		$info = $materialStockCuttingService->getInfoById($id);
    	} else {
    		$info = $orderMaterialItemService->getInfoById($id);
    	}
    	if (!$info) {
			return $this->error('数据异常');
    	}

    	$orderId = $info['order_id'];
    	$clientOrdernum = $info['client_ordernum'];
    	$materialId = $info['material_id'];
    	$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);

    	if ($this->request->isAjax()) {
    		$tableArr = $this->request->param('table/a', []);
    		$caichuangTWheatLowArr = $this->request->param('caichuang_t_wheat_low/a', []);
    		$caichuangTWheatHeightArr = $this->request->param('caichuang_t_wheat_height/a', []);
    		$caichuangTStripArr = $this->request->param('caichuang_t_strip/a', []);
    		$caichuangTNeadendArr = $this->request->param('caichuang_t_neadend/a', []);
    		$caichuangRemarkArr = $this->request->param('caichuang_remark/a', []);

    		try {
    			db()->startTrans();

    			foreach ($tableArr as $tid => $tvalue) {
	    			$upData = [
	    				'caichuang_t_wheat_low' => floatval($caichuangTWheatLowArr[$tid]),
	    				'caichuang_t_wheat_height' => floatval($caichuangTWheatHeightArr[$tid]),
	    				'caichuang_t_strip' => floatval($caichuangTStripArr[$tid]),
	    				'caichuang_t_neadend' => floatval($caichuangTNeadendArr[$tid]),
	    				'caichuang_remark' => $caichuangRemarkArr[$tid],
	    				'update_time' => time(),
	    			];
	    			db($tvalue==0?'order_material_item':'material_stock_cutting')->where('id', $tid)->update($upData);
    			}

    			// 更新order_material表实际裁剪信息
    			$omiList = $orderMaterialItemService->getListByOrderMaterialId($omInfo['mid']);
    			$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $materialId);

    			$upData = [
    				'caichuang_t_wheat_low' => array_sum(array_column($omiList, 'caichuang_t_wheat_low')) + arrayGet($mscInfo, 'caichuang_t_wheat_low', 0),
    				'caichuang_t_wheat_height' => array_sum(array_column($omiList, 'caichuang_t_wheat_height')) + arrayGet($mscInfo, 'caichuang_t_wheat_height', 0),
    				'caichuang_t_strip' => array_sum(array_column($omiList, 'caichuang_t_strip')) + arrayGet($mscInfo, 'caichuang_t_strip', 0),
    				'caichuang_t_neadend' => array_sum(array_column($omiList, 'caichuang_t_neadend')) + arrayGet($mscInfo, 'caichuang_t_neadend', 0),
    				'update_time' => time(),
    			];
    			// 计算实裁数
    			$orderSizeService = new OrderSizeService();
    			$osList = $orderSizeService->getListByOrderId($orderId);
    			$shicaiCount = 0;
    			foreach ($osList as $v) {
    				$shicaiCount += arrayGet($v['wheat_low_count_detail'], $omInfo['mid'], 0)*$upData['caichuang_t_wheat_low'] + arrayGet($v['wheat_height_count_detail'], $omInfo['mid'], 0)*$upData['caichuang_t_wheat_height'];
    			}
    			$upData['shicai_count'] = $shicaiCount;

    			// 计算实际单件用量=(唛架总长度/总件数)+裁床捆条单件用量
    			if($omInfo['caichuang_t_wheat_low_number']+$omInfo['caichuang_t_wheat_height_number'] > 0) {
    				$upData['caichuang_shiji_dosage'] = $omInfo['caichuang_strip_dosage'] + round(($omInfo['caichuang_t_wheat_low_length']+$omInfo['caichuang_t_wheat_height_length'])/($omInfo['caichuang_t_wheat_low_number']+$omInfo['caichuang_t_wheat_height_number']), 2);
    			}
    			db('order_material')->where('order_id', $orderId)->where('material_id', $materialId)->update($upData);

    			$this->addOrderLog($orderId, $clientOrdernum, "面料[{$omInfo['mInfo']['name']}]实裁数据录入");
    			db()->commit();

    			return $this->Json(1, '操作成功', ['url' => url('task', ['client_ordernum' => $clientOrdernum, 'mid' => $omInfo['mid']], true, true) . '#m'. $omInfo['mid']]);
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}

    	}

    	$omiList = $orderMaterialItemService->getListByOrderMaterialId($omInfo['mid']);
    	$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $materialId);
    	if($mscInfo) {
    		$mscInfo['is_msc'] = 1;
    		array_push($omiList, $mscInfo);
    	}

    	$assign = [
    		'id' => $id,
    		'type' => $type,
    		'omInfo' => $omInfo,
    		'omiList' => $omiList,
    	];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 拉布确认
     *
     * @author King
     * @date 2020年9月3日
     *
     */
    public function confirm() {
    	$mid = $this->request->param('mid/d', 0); // order_material表ID
    	$caichuangFabricWidth = $this->request->param('caichuang_fabric_width/f', 0);
    	$wheatLowBundleDetail = $this->request->param('wheat_low_bundle_detail/a', []);	// 低层多少件合成一扎
    	$wheatHeightBundleDetail = $this->request->param('wheat_height_bundle_detail/a', []);	// 高层多少件合成一扎
        $have_oddments=$this->request->param('have_oddments/d', 0);
    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
    	$materialStockCuttingService = new MaterialStockCuttingService();
		$orderExceptionService=new OrderExceptionService();
    	$omInfo = $orderMaterialService->getInfoById($mid);
    	if (empty($omInfo)) {
    		return $this->error('数据异常');
    	}
    	try {
    		db()->startTrans();

    		$orderId = $omInfo['order_id'];
    		$clientOrdernum = $omInfo['client_ordernum'];
    		$materialId = $omInfo['material_id'];

    		// 更新order_material表caichuang_pull_status状态
    		$upData = [
    			'caichuang_fabric_width' => $caichuangFabricWidth,
    			'caichuang_pull_status' => 1,
    			'caichuang_pull_time' => time(),
    			'caichuang_over_time' => time(),
    			'update_time' => time(),
    		];
    		db('order_material')->where('mid', $mid)->update($upData);
    		if($have_oddments==1){
                $oddmentsMeters =$this->request->param('oddments_meters', 0);
                $storeHouse =$this->request->param('storeHouse',0);
                $stockPosition =$this->request->param('stock_position');
                $arr=[];
                $arr['audit_status'] = 1;
                $arr['cutting_time'] = time();
                $arr['action_adminid']=ADMIN_ID;
                $arr['material_id'] = $omInfo['material_id'];
                $arr['factory_id'] = $omInfo['factory_id'];
                $arr['order_id'] = $omInfo['order_id'];
                $arr['client_ordernum'] = $omInfo['client_ordernum'];
                $arr['metre'] = $oddmentsMeters;
                $arr['metre_left'] = $oddmentsMeters;
                $arr['weight'] = 0;
                $arr['unit_price'] =$omInfo['customer_price'];
                $arr['amount'] = $omInfo['customer_price']*$oddmentsMeters;
                $arr['unit_price_metre'] = $omInfo['customer_price'];
                $arr['amount_type'] = 2;
                $arr['storehouse_id'] =$storeHouse;
                $arr['storeshelf_id'] = $stockPosition;
                $arr['create_time'] = $arr['update_time'] = time();
                $result = db('material_stock')->insertGetId($arr);
                //生成.余料入库申请 oddments_meters
                $applyCheckInInfo[] = [
                    'stock' => $oddmentsMeters,
                    'material_id' => $omInfo['material_id'],
                    'in_factory' => $omInfo['factory_id'],
                    'stock_m_type' => 2,
                    'client_ordernum' => $omInfo['client_ordernum'],
                    'order_id' => $omInfo['order_id'],
                    'sku' => '',
                    'cloth_num' => '1-1',
                    'storehouse_id' => $storeHouse,
                    'storeshelf_id' => $stockPosition,
                    'remark' => "裁剪有作料,余料id:".$result,
                ];
                $stockServer = new StockService();
                $changeStockList = $stockServer->applyCheckIn($applyCheckInInfo,'裁剪有余料');
            }

    		// 更新order表 床号/执行人
    		$upData = [
    			'caichuang_chuanghao' => $orderId,
    			'caichuang_user_id' => ADMIN_ID,
    			'update_time' => time(),
    		];
    		db('order')->where('id', $orderId)->update($upData);
            //初始化 订单工价-对帐单表 wx_order_progress_price
//            $res3 = (new \app\common\service\ProcessPriceOrder())->cutting_confirm_add($orderId);

    		// 客户用量最大的物料需生成扎数
    		if ($omInfo['caichuang_standard'] == 1) {
    			$orderSizeService = new OrderSizeService();

    			// 更新尺码多少件合成一扎
    			foreach ($wheatLowBundleDetail as $osMid => $osBundle) {
    				$osBundle = intval($osBundle);
    				$osInfo = $orderSizeService->getInfoById($osMid);
    				if (arrayGet($osInfo['wheat_low_count_detail'], $mid, 0) < $osBundle) {
    					throw new \Exception("低层 {$osInfo['size_name']} 的合成扎件数填写错误");
    				}

    				$osInfo['wheat_low_bundle_detail'][$mid] = $osBundle;
    				db('order_size')->where('mid', $osMid)->update(['wheat_low_bundle_detail' => json_encode($osInfo['wheat_low_bundle_detail'])]);
    			}
    			foreach ($wheatHeightBundleDetail as $osMid => $osBundle) {
    				$osBundle = intval($osBundle);
    				$osInfo = $orderSizeService->getInfoById($osMid);
    				if (arrayGet($osInfo['wheat_height_count_detail'], $mid, 0) < $osBundle) {
    					throw new \Exception("高层 {$osInfo['size_name']}码 的合成扎件数填写错误");
    				}

    				$osInfo['wheat_height_bundle_detail'][$mid] = $osBundle;
    				db('order_size')->where('mid', $osMid)->update(['wheat_height_bundle_detail' => json_encode($osInfo['wheat_height_bundle_detail'])]);
    			}


    			// 生成扎数
    			$orderUserService = new OrderUserService();
    			$zhahaoJinpengDel = [];// 金鹏需删除的扎号
    			$orderUserService->makeBundle($orderId, false, $zhahaoJinpengDel);

    			// 计算各尺码实裁数
    			$osList = $orderSizeService->getListByOrderId($orderId);
    			$material_shicai_count=0;
    			foreach ($osList as $v) {
    				$shicaiCount = arrayGet($v['wheat_low_count_detail'], $omInfo['mid'], 0)*$omInfo['caichuang_t_wheat_low'] + arrayGet($v['wheat_height_count_detail'], $omInfo['mid'], 0)*$omInfo['caichuang_t_wheat_height'];
    				db('order_size')->where('mid', $v['mid'])->update(['shicai_count' => $shicaiCount, 'update_time' => time()]);
                    $material_shicai_count+=$shicaiCount;
    			}
                db('order_material')->where('mid', $mid)->update(['shicai_count'=>$material_shicai_count]);
    		}

    		// 是否全部拉布确认
    		$omList = $orderMaterialService->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
    		$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $materialId);
    		if (array_sum(array_column($omList, 'caichuang_pull_status')) == count($omList)) {

    			// 更新订单表，标识订单已裁剪完成
    			$oInfo = $orderService->getInfoById($orderId, 'caichuang_over_time');
    			$orderData = [
    				'caichuang_status' => 1,
    			];
    			if(!$oInfo['caichuang_over_time']) $orderData['caichuang_over_time'] = time();
    			db('order')->where('id', $orderId)->update($orderData);
    		}

    		// 是否需要进入配料仓库
    		if ($orderMaterialService->checkNeedDistributing($orderId)) {	// 需要进入配料仓库
	    		// 自动同步到配料区
	    		$orderService = new OrderService();
	    		$distributingService = new DistributingService();
	    		$orderInfo = $orderService->getInfoById($orderId);
    			$distributingInfo = $distributingService->getInfoByOrderId($orderId);
    			if (!$distributingInfo) {
    				$distributingData = [
    					'factory_id' => $orderInfo['factory_id'],
    					'order_id' => $orderId,
    					'client_ordernum' => $orderInfo['client_ordernum'],
    					'is_read' => 0,
    					'status' => 1,
    					'create_time' => time(),
    					'update_time' => time(),
    				];
    				db('distributing')->insertGetId($distributingData);
    			}

    		}
			$exception=0;$msg="此款需核价请留布头给裁床主管</br>";
			$dif1 = $orderMaterialService->checkCaichuangLossStatus1($omInfo['mid']);
			if ($dif1) {
				$exception=1;//裁床1损耗大于0.02 true=1 ,false=0
				$msg="该单物料亏损严重，差异".$dif1."件</br>";
			}
			$dif2 = $orderMaterialService->checkCaichuangLossStatus2($omInfo['mid']);
			if ($dif2) {
				$exception=0; //拉布确认增加了余料确认，不再文字提醒差异
				$msg=$msg."该单物料亏损严重，差异".$dif2."米";
			}
			$orderUserOriMap = db('order_user')->where('order_id', $orderId)->column('jinpeng_status,jinpeng_qty,jinpeng_size_name,jinpeng_chuanghao,mid,chuanghao,size_name,jianshu,create_time', 'zhahao');

    		$this->addOrderLog($orderId, $clientOrdernum, "面料[{$omInfo['mInfo']['name']}]拉布确认");
    		db()->commit();
			if(isset($zhahaoJinpengDel) && !empty($zhahaoJinpengDel)){
    			// 通知金鹏删除扎号
				foreach ($zhahaoJinpengDel as $kd => $vd) {
					$orderUserOriMap[$vd]['jinpeng_status']=4;
					$jinPengDelData[]=$orderUserOriMap[$vd];
				}
				$orderService->syncJinpengCut($orderId,'edit','dele',$jinPengDelData);
    		}
    		return $this->Json(1, '操作成功', ['url' => url('task', ['client_ordernum' => $clientOrdernum], true, true),'exception'=>$exception,'msg'=>$msg]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 菲码打印
     *
     * @author KING
     * @date 2020年7月20日
     *
     */
    public function fecode() {
    	$orderId = $this->request->param('order_id/d', 0);
    	$mid = $this->request->param('mid/d', 0);
    	$orderService = new OrderService();
    	$skuService = new SkuService();
    	$orderUserService = new OrderUserService();
    	$orderMaterialService = new OrderMaterialService();
    	$assign = [];
    	$assign['orderId'] = $orderId;
    	$assign['ouList'] = $orderUserService->getListByOrderId($orderId);
    	if ($mid > 0) {
    		foreach ($assign['ouList'] as $k => $v) {
    			if ($v['mid'] != $mid) {
    				unset($assign['ouList'][$k]);
    			}
    		}
    	}
    	if (empty($assign['ouList'])) return $this->error('还未进行实裁数录入');

    	foreach ($assign['ouList'] as $k => $v) {
    		$msg = implode(',', [2, $v['mid'], $v['client_ordernum'], $v['zhahao'], $v['jianshu'], $v['size_name']]);
    		$qrCode = new QrCode($msg);
    		$assign['ouList'][$k]['qrcode'] = $qrCode->writeDataUri();
    	}

    	$this->view->engine->layout('system@layout_empty');
    	return $this->assign($assign)->fetch();
    }

    /**
     * 裁床单打印
     * @author KING
     * @date 2020年7月17日
     */
    public function print() {
    	$orderId = $this->request->param('order_id/d', 0);
    	$orderService = new OrderService();
    	$skuService = new SkuService();
    	$orderSizeService = new OrderSizeService();
    	$orderUserService = new OrderUserService();

    	$assign = [];
    	$assign['orderId'] = $orderId;
    	$assign['oInfo'] = $orderService->getInfoById($orderId);
    	$assign['sInfo'] = $skuService->getInfoBySku($assign['oInfo']['sku']);
		$osList= $orderSizeService->getListByOrderId($orderId);
		$ouList= $orderUserService->getListByOrderId($orderId);
		foreach ($osList as $kos => $vos) {
			$osList[$kos]['shicai_jianshu']=0;
			foreach ($ouList as $kou => $vou) {
				if($vos['size_name']==$vou['size_name']) $osList[$kos]['shicai_jianshu']=$osList[$kos]['shicai_jianshu']+$vou['jianshu'];
			}
		}
    	$assign['osList']=$osList;
    	$assign['ouList']=$ouList;
    	$assign['systemUserKV'] = getSystemUserKV(null);

    	$this->view->engine->layout('system@layout_empty');		//dump($osList);
    	return $this->assign($assign)->fetch();
    }

    /**
     * 切片打包外发打标
     */
    public function cutPackageLabel(){
        $orderId = $this->request->param('order_id/d', 0);
        $action=$this->request->param('action');
        $where[] = ['a.id', '=', $orderId];
        $orderInfo=db('order a')->join('order_ext ext', 'a.id = ext.order_id','left')
            ->join('factory_outgo outgo', 'outgo.id = a.factory_outgo_id','left')
            ->field('a.factory_id,a.group_id,a.factory_outgo_id,ext.cut_packages,ext.cut_packages_remark,outgo.address,outgo.mobile,a.client_ordernum')->where($where)->find();
        $factoryKV = getFactoryKV(false);
        $factoryOutgoKV = getFactoryOutgoKV(null);
        $groupKV = getGroupKV(0);
        $factoryKV[0]='未分配';
        $factoryOutgoKV[0]='未分配';
        $groupKV[0]='未分配';
        $orderInfo['cut_packages_remark']= empty($orderInfo['cut_packages_remark']) ? '裁片' : $orderInfo['cut_packages_remark'];
        $orderInfo['factory_name']=isset($factoryKV[$orderInfo['factory_id']]) ? $factoryKV[$orderInfo['factory_id']] : '未分配' ;
        $orderInfo['group_name']=isset($groupKV[$orderInfo['group_id']]) ? $groupKV[$orderInfo['group_id']] : '未分配' ;
        $orderInfo['factory_outgo_name']=isset($factoryOutgoKV[$orderInfo['factory_outgo_id']]) ? $factoryOutgoKV[$orderInfo['factory_outgo_id']] : '' ;
        //factory_name group_name factory_outgo_name
        if(!empty($action)){
            $cut_packages = $this->request->param('cut_packages/d', 0);
            $cut_packages_remark = $this->request->param('cut_packages_remark');
            if($cut_packages<=0){
                echo "<script>alert('打标包数必须大于0，请返回确认');window.close();</script>";
            }
            $msg = $orderInfo['client_ordernum'];
            $qrCode = new QrCode($msg);
            //$assign['ouList'][$k]['qrcode'] = $qrCode->writeDataUri();
            $orderInfo['qrcode']= $qrCode->writeDataUri();
            db("order_ext")->where([['order_id','=',$orderId]])->update(['cut_packages'=>$cut_packages,'cut_packages_remark'=>$cut_packages_remark]);
            $orderInfo['cut_packages']=$cut_packages;
            $orderInfo['cut_packages_remark']=$cut_packages_remark;
            $assigndata['oInfo']=$orderInfo;
            return $this->assign($assigndata)->fetch();
        }
        return $this->Json(1, '', $orderInfo);

    }

    /**
     * 扎菲票打印
     */
    public function cutSizeLabel(){
        $orderId = $this->request->param('order_id/d', 0);
        $action=$this->request->param('action');
        $where[] = ['a.id', '=', $orderId];
        $cut_bars=$this->request->param('cut_bars');
        $packeg_remark=$this->request->param('packeg_remark');
        $requestdata=$this->request->get();
        //$info = db('order_user')->where("order_id = {$orderId} and zhahao = {$val}")->findOrEmpty();
        $orderInfo=db('order a')->join('order_ext ext', 'a.id = ext.order_id','left')
            ->join('factory_outgo outgo', 'outgo.id = a.factory_outgo_id','left')
            ->field('a.factory_id,a.group_id,a.factory_outgo_id,ext.cut_packages,ext.cut_packages_remark,outgo.address,outgo.mobile,a.client_ordernum')->where($where)->find();
        if(empty($action) || $action=='cut_size_label_set'){
            $factoryKV = getFactoryKV(false);
            $factoryOutgoKV = getFactoryOutgoKV(null);
            $groupKV = getGroupKV(0);
            $factoryKV[0]='未分配';
            $factoryOutgoKV[0]='未分配';
            $groupKV[0]='未分配';
            $orderInfo['cut_packages_remark']= empty($orderInfo['cut_packages_remark']) ? '裁片' : $orderInfo['cut_packages_remark'];
            $orderInfo['factory_name']=isset($factoryKV[$orderInfo['factory_id']]) ? $factoryKV[$orderInfo['factory_id']] : '未分配' ;
            $orderInfo['group_name']=isset($groupKV[$orderInfo['group_id']]) ? $groupKV[$orderInfo['group_id']] : '未分配' ;
            $orderInfo['factory_outgo_name']=isset($factoryOutgoKV[$orderInfo['factory_outgo_id']]) ? $factoryOutgoKV[$orderInfo['factory_outgo_id']] : '' ;
            return $this->assign($orderInfo)->fetch();
        }

        if(!empty($action)){
            $zhahaos = explode(',', $requestdata['cut_bars']);
            $other_remark = $this->request->param('other_remark');
            $packeg_remark = $this->request->param('packeg_remark');
            $is_cut_merge=$this->request->param('is_cut_merge');
            $clientOrdernumArr=$requestdata['client_ordernum'];
            if(count($requestdata['client_ordernum'])<=0 || count($zhahaos)<=0){
                echo "<script>alert('打印的订单与扎号不能为空,您未选择');window.close();</script>";
            }
            $colnumName=$is_cut_merge==0 ? "order_id" : 'client_ordernum';
            $orderColnumName=$is_cut_merge==0 ? "id" : 'client_ordernum';
            $order_dress_color=db('order')->where([[$orderColnumName,'in',$clientOrdernumArr]])->column("dress_color",'client_ordernum');
            $zhahaoList=db('order_user')->where([[$colnumName,'in',$clientOrdernumArr],['zhahao','in',$zhahaos]])->order('client_ordernum asc,zhahao asc')->select();
            $qrCode = new QrCode();
            foreach ($zhahaoList as $key=>&$zhahaoinfo){
                $qrCode->setText($zhahaoinfo['client_ordernum'].'-'.$zhahaoinfo['zhahao']);
                $zhahaoinfo['qrcode']= $qrCode->writeDataUri();
                $zhahaoinfo['dress_color']=$order_dress_color[$zhahaoinfo['client_ordernum']];
            }
            $weekarr=['日','一','二','三','四','五','六'];
            $assigndata['today']=date("Y-m-d");
            $assigndata['week']="星期".$weekarr[date("w")];
            $assigndata['other_remark']=$other_remark;
            $assigndata['packeg_remark']=$packeg_remark;
            $assigndata['zhahaolist']=$zhahaoList;
            return $this->assign($assigndata)->fetch();
        }

    }

    /*裁库余料库存面单打印*/
    public function materialStockLabel(){
        $material_stock_id= $this->request->param('material_stock_id', '');
        $where = [
            ['id', '=', $material_stock_id],
        ];
        if($material_stock_id==''){
            echo "<script>alert('缺少必要参数');window.close();</script>";
        }
        $materialStockInfo=db('material_stock')->where($where)->order("id asc")->find();
        $materialStockInfo['printr_date']=date("Y-m-d H:i");
        $materialStockInfo['mInfo'] = db('material')->where('id', $materialStockInfo['material_id'])->field('name,material_sku,color')->findOrEmpty();
        $msg = $materialStockInfo['client_ordernum'];
        $qrCode = new QrCode($msg);
        $materialStockInfo['qrcode']= $qrCode->writeDataUri();
        $materialStockList[]=$materialStockInfo;
        $assign['stock_list']=$materialStockList;

        return $this->assign($assign)->fetch();
    }

	/**
	 * 裁床面板/电脑裁床
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @return string
	 */
    public function panel()
    {
		$factoryKV = getFactoryKV(false);
    	$caichuangType = $this->request->param('caichuang_type/d', 0);
        if ($this->request->isPost()) {
        	$where = [];
        	$where[] = ['caichuang_status', '=', 0];
        	$where[] = ['status', 'in', [0, 1]];
			$factorId      = $this->request->param('factory_id/s', '');
            $caichuangCando    = $this->request->param('caichuang_can_do/d',-1);
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $shipmentTime    = $this->request->param('shipment_time/s','');
            $materialSku    = $this->request->param('material_sku/s','');
			if ($factorId!='') {
                    $where[] = ['factory_id', 'in', $factorId];
            }
            if ($shipmentTime != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $shipmentTime));
                $where[] = ['shipment_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($clientOrdernum != '') {
                $where[] = ['client_ordernum', '=', $clientOrdernum];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
            //订单加一级
            order_level($where,'');
            if ($caichuangCando != -1) {
                $where[] = ['caichuang_can_do', '=', $caichuangCando];
            }
        	if ($materialSku != '') {
        		$materialId = db('material')->where('material_sku', $materialSku)->value('id', 0);
        		$orderIds = ($materialId==0) ? [0] : db('order_material')->where('material_id', $materialId)->column('order_id');
        		$where[] = ['id', 'in', $orderIds];
        	}
        	$list = db('order')->where($where)->order('shipment_time desc')->select();
        	$skus = array_column($list, 'sku');

        	// 是否有同物料
        	$orderHasSameMaterialMap = [];
        	$orderIds = array_column($list, 'id');
        	if ($orderIds) {
        		$listB = $listC = [];
        		$listA = db('order_material om')->join('material m', 'om.material_id=m.id')->where('om.order_id', 'in', $orderIds)->where('m.type', 'in', ['fabric','lining'])->field('m.material_sku,om.order_id')->select();
        		foreach ($listA as $v) {
        			$listB[$v['material_sku']][] = $v['order_id'];
        			$listC[$v['order_id']][] = $v['material_sku'];
        		}
        		unset($listA);
        		foreach ($listC as $orderId => $materialSkuArr) {
        			foreach ($materialSkuArr as $ms) {
        				if (count($listB[$ms]) > 1) {
        					$orderHasSameMaterialMap[$orderId] = $ms;
        					break;
        				}
        			}
        		}
        		unset($listB, $listC);
        	}


        	$skuKV = db('sku')->where('sku', 'in', $skus)->column('ori_pic', 'sku');
        	$factoryOutgoKV = getFactoryOutgoKV(null);
			$factoryKV = getFactoryKV(null);
        	$groupKV = [0 => '未分组'] + getGroupKV();

        	$key = 'caichuang';
        	$result = [];
        	foreach ($list as $v) {
        		$result[$v['group_id']]['name'] = arrayGet($groupKV, $v['group_id'], '');

        		$result[$v['group_id']][$key][] = [
					'order_id' => $v['id'],
        			'client_ordernum' => $v['client_ordernum'],
        			'sku' => $v['sku'],
        			'quantity' => $v['quantity'],
        			'shipment_time' => date("m-d", $v['shipment_time']),
        			'factory_outgo_name' => arrayGet($factoryOutgoKV, $v['factory_outgo_id'], ''),
					'factory_name' => arrayGet($factoryKV, $v['factory_id'], ''),
					'caichuang_can_do'=>$v['caichuang_can_do']== 1 ? '可裁剪':'不可裁剪',
					'type' => arrayGet(config('mimo.order_type'), $v['type'], ''),
        			'pic' => arrayGet($skuKV, $v['sku'], ''),
        			'tags' => getOrderTag($v),
        			'same_material_sku' => arrayGet($orderHasSameMaterialMap, $v['id'], ''),
        		];
        		if (isset($result[$v['group_id']][$key.'_orders'])) {
        			$result[$v['group_id']][$key.'_orders']++;
        		} else {
        			$result[$v['group_id']][$key.'_orders']=1;
        		}

        		if (isset($result[$v['group_id']][$key.'_items'])) {
        			$result[$v['group_id']][$key.'_items']+=$v['quantity'];
        		} else {
        			$result[$v['group_id']][$key.'_items']=$v['quantity'];
        		}
        	}

        	return $this->Json(1, '', $result);
        }
		$assign=[
			'factoryKV' => [0 => '请选择'] + $factoryKV,
			'caichuangType'=>$caichuangType
		];
        return $this->assign($assign)->fetch();
    }

	public function getQuantityDetail(){
		$orderId =$this->request->param('order_id/id',0);
		$orderSizeService=new OrderSizeService();
		$osList=$orderSizeService->getListByOrderId($orderId, 'size_name,order_count');
		$osList[]=['size_name'=>'合计','order_count'=>array_sum(array_column($osList,'order_count'))];
		$data['data']=$osList;
		return $data;
	}
	/**
	 * 裁床面板订单操作日志
	 *
	 * @author 飞燕
	 * @date 2021年2月22日
	 *
	 * @return string
	 */
	public function logDetail(){
		$orderId    = $this->request->param('order_id/d',0);
		$mid    = $this->request->param('mid/d',0);
		$orderMaterialService = new OrderMaterialService();
		if ($this->request->isAjax()) {
			$omInfo=$orderMaterialService->getInfoById($mid);
			$list=[];
			if(!empty($omInfo)){
				if($omInfo['caigou_confirm_status']!=0){
					$list['caigou_confirm_status']=[
						'remark'=>'已开始采购',
						'time'=>$omInfo['caigou_confirm_time'],
						'admin'=>''
					];
				}
				if($omInfo['arrive_time']!=0){
					$list['caigou']=[
						'remark'=>'已到料',
						'time'=>$omInfo['arrive_time'],
						'admin'=>''
					];
				}
				if($omInfo['is_make_tag']!=0){
					$list['is_make_tag']=[
						'remark'=>'已打标',
						'time'=>$omInfo['caigou_confirm_time'],
						'admin'=>''
					];
				}
				if($omInfo['caigou_status']!=0){

					$list['caigou_status']=[
						'remark'=>$omInfo['caigou_status']==1 ? '面料已批色' : '面料批色不通过',
						'time'=> $omInfo['caigou_over_time'],
						'admin'=>''
					];
				}
			}
			$rmInfo=db('material_return')->where('order_material_id', $mid)->field('*')->findOrEmpty();
			if(!empty($rmInfo)){
				$systemUserKV = getSystemUserKV(true);
				$list['material_return']=[
					'remark'=>'物料发起退料',
					'time'=>$rmInfo['create_time'],
					'admin'=>arrayGet($systemUserKV, $rmInfo['admin_id'], '')
				];
			}
			$cInfo=db('checkcloth_shrink cs')->join('order_material_item omi', "cs.order_material_item_id=omi.id", 'left')->where('omi.order_material_id='.$mid.' and cs.type=1')->field('*')->findOrEmpty();
			if(!empty($cInfo)){
				$systemUserKV = getSystemUserKV(true);
				if($cInfo['is_checkcloth']!=0){
					$list['checkCloth']=[
						'remark'=>'已验布',
						'time'=>$cInfo['create_time'],
						'admin'=>arrayGet($systemUserKV, $cInfo['admin_id'], '')
					];
				}
			}
			$sInfo=db('checkcloth_shrink cs')->join('order_material_item omi', "cs.order_material_item_id=omi.id", 'left')->where('omi.order_material_id='.$mid.' and cs.type=2')->field('*')->findOrEmpty();
			if(!empty($sInfo)){
				$systemUserKV = getSystemUserKV(true);
				if($sInfo['is_checkcloth']!=0){
					$list['shrink']=[
						'remark'=>'已缩水',
						'time'=>$sInfo['create_time'],
						'admin'=>arrayGet($systemUserKV, $sInfo['admin_id'], '')
					];
				}
			}
			$data['data']=[];
			$time = array_column($list,'time');
			array_multisort($time,SORT_DESC,$list);
			$id=1;
			foreach ($list as $key => $value) {
				$value['id']=$id++;
				$data['data'][]=$value;
			}
			$data['count'] = sizeof($data['data']);
			$data['code'] = 0;
            $data['msg'] = '';
			return json($data);
		}
		// 条数统计
    	//$statData = db('material_return')->group('status')->fieldRaw('status,count(status)')->column('count(status)', 'status');
		$omData = $orderMaterialService->getListByOrderId($orderId);
		$statusMap=[];
		foreach ($omData as $kom => $vom) {
			$statusMap[$vom['mid']]=$vom['mInfo']['name'];
			if($mid==0) $mid=$omData[0]['mid'];
		}
    	$tabData['menu'] = [];
    	foreach ($statusMap as $k => $v) {
    		$tabData['menu'][] = [
    			'title' => $v ,//. '（<span class="red bold stat-num-'.$k.'">' . arrayGet($statData, $k, 0) . '</span>条）'
    			'url' => 'mp/Cutting/logDetail?order_id='.$orderId.'&mid=' . $k,
    		];
    	}
    	$tabData['current'] = url('mp/Cutting/logDetail?order_id='.$orderId.'&mid='.$mid);
    	$assign = [
    		'hisiTabData' => $tabData,
    		'hisiTabType' => 3,
    		'mid' => $mid,
			'orderId' => $orderId,
    	];
		return $this->assign($assign)->fetch();
	}
    /**
     * 裁床报表
     *
     * @author King
     * @date 2020年8月27日
     *
     */
    public function report() {
        $userService=new UserService();
        $userKV=$userService->getKVList(null);
        $factoryKV = getFactoryKV(false);
    	$factoryOutgoKV = getFactoryOutgoKV(null);
    	$systemUserKV = getSystemUserKV(null);
        $groupKV = getGroupKV(0);
		$stallsKV = getStallsKV();
		$orderSizeService = new OrderSizeService();
        $cuttingService=new CuttingService();
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where      = $data = [];
			$stat = $this->request->param('a/s','');
			$statCondition = $this->request->param('sc/s','');
            $factorId      = $this->request->param('factory_id/s', '');
            $sku    = $this->request->param('sku/s');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $createDateRange    = $this->request->param('create_date_range/s');
            $caiChuangType    = $this->request->param('caichuang_type/d');
            $caichuangOverDateRange  = $this->request->param('caichuang_over_date_range/s');
            $statType    = $this->request->param('stat_type/s', '');
            $export     = $this->request->param('export/d', 0);
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $caiChuangUserId= $this->request->param('caichuang_user_name/s');
            $keyword    = $this->request->param('keyword/s');
            $isOmc  = $this->request->param('is_omc/d', 2);
			$detailWhere=[
				'factory_id'=>$factorId,
				'sku'=>$sku,
				'client_ordernum'=>$clientOrdernum,
				'create_date_range'=>$createDateRange,
				'caichuang_type'=>$caiChuangType,
				'caichuang_over_date_range'=>$caichuangOverDateRange,
				'stat_type'=>$statType,
				'caichuang_user_name'=>$caiChuangUserId,
			];
            if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}

            $where[] = ['status', 'in', [0,1,2]];
            //订单加一级
            order_level($where,'');
            if ($factorId) {
                    $where[] = ['factory_id', 'in', $factorId];
            }

            if ($caiChuangUserId){
                $where[] = ['caichuang_user_id', 'in', $caiChuangUserId];
            }
            if ($statType != '') {
                    $cacheKeyMap = ['cg' => STAT_CG, 'cj' => STAT_CJ,'chej' => STAT_CHEJ, 'wb' => STAT_WB,'dch' => STAT_DCH, 'hj' => STAT_HJ,'cpwf_cg' => STAT_CPWFCG, 'cpwf_cj' => STAT_CPWFCJ,'cpwf_hj' => STAT_CPWFHJ];
                    $cacheKey = arrayGet($cacheKeyMap, $statType, '') . ADMIN_ID;
                    $where[] = ['id', 'in', cache($cacheKey)];
            }

            if ($clientOrdernum != '') {
                    $where[] = ['client_ordernum', '=', $clientOrdernum];
            }
            if ($isOmc!=2) { //是否合裁搜索
                $subQueryo = db('order_merge_cut')->distinct(true)->field('client_ordernum')->select();
                $clientOrdernums=[];
                foreach ($subQueryo as $komc => $vomc) {
                    $orderNumStr= arrayGet($vomc, "client_ordernum",'');
                    $orderNumArr= explode(',', $orderNumStr);
                    $clientOrdernums= array_merge($clientOrdernums,$orderNumArr);
                }
                $where[] = ['client_ordernum', 'in', $clientOrdernums];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
            if ($sku != '') {
                    $where[] = ['sku', '=', $sku];
            }
            if ($keyword) {
                    $where[] = ['remark', 'like', "%{$keyword}%"];
            }
            if ($caiChuangType != '') {
                $where[] = ['caichuang_type', '=', $caiChuangType];
            }
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
            }

            if ($caichuangOverDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
                $where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
            }
            $where[] = [
                ['caichuang_over_time', '<>', 0],
				['status', '<>',99],
				['stock_type','not in','10,11']
			];
			if($statCondition!=""){
				switch ($statCondition){
					case "caichuangOverCount": // 已裁床单数
    					break;
					case "acOverCount": // 辅料发放单数
//						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
//    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
//    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
//    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
//						$where[] = ['caichuang_over_time', '<>', 0];
    					$subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
    					break;
					case "acNotCount": // 辅料未发放单数
//						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
//    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
//						$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
//    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
//						$where[] = ['caichuang_over_time', '<>', 0];
    					$subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery3})")];
    					break;
					case "acNoCount": //辅料采购未完成
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery1})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
				}
				$where[] = ['stock_type', 'not in', '10,11'];
			}
            $order = 'ord.id desc';
            $field1='ord.id,cut_pr.process_price,caichuang_over_time,client_ordernum,ord.sku,quantity,caichuang_chuanghao,caichuang_user_id,caichuang_type,caichuang_position,`factory_id`';
            $field2='customer_dosage,shicai_count,caichuang_t_wheat_low_length,caichuang_t_wheat_low,caichuang_t_wheat_height_length,caichuang_t_wheat_height,caichuang_t_wheat_low_number,caichuang_t_wheat_height_number,caichuang_t_wheat_height,caichuang_t_wheat_low,caichuang_wheat_low_length,caichuang_wheat_low,caichuang_wheat_height_length,caichuang_wheat_height,checkcloth_length,shrink_length,need_checkcloth,need_shrink,billing_caigou_count,caichuang_t_strip,caichuang_t_neadend,caichuang_shiji_dosage as caichuang_shiji_dosage';
            $data['data']=db('order ord')
                ->join('order_progress_price_change cut_pr', 'cut_pr.process_keywords="caijian" and cut_pr.order_id=ord.id', 'left')
                ->where($where)->field($field1)->page($page)->limit($limit)->order($order)->select();
            $skuService = new SkuService();
			$idUserKV=$userService->getKVList(null);
            $orderMergeCutService = new OrderMergeCutService();
            foreach ($data['data'] as $k => $v) {
                $omInfoData=[
                    'customer_dosage'=>'',
                    'shicai_count'=>'',
                    'caichuang_t_wheat_low_length'=>'',
                    'caichuang_t_wheat_low'=>'',
                    'caichuang_t_wheat_height_length'=>'',
                    'caichuang_t_wheat_height'=>'',
                    'caichuang_t_wheat_low_number'=>'',
                    'caichuang_t_wheat_height_number'=>'',
                    'caichuang_t_wheat_height'=>'',
                    'caichuang_t_wheat_low'=>'',
                    'caichuang_wheat_low_length'=>'',
                    'caichuang_wheat_low'=>'',
                    'caichuang_wheat_height_length'=>'',
                    'caichuang_wheat_height'=>'',
                    'checkcloth_length'=>'',
                    'shrink_length'=>'',
                    'need_checkcloth'=>'',
                    'need_shrink'=>'',
                    'billing_caigou_count'=>'',
                    'caichuang_t_strip'=>'',
                    'caichuang_t_neadend'=>'',
                    'caichuang_shiji_dosage'=>'',
                ];
                $omWhere=[
                    ['order_id','=',$v['id']],
                    ['caichuang_standard','=',1],
                ];

                $omcInfo=$orderMergeCutService->getInfoByClientOrdernum($v['client_ordernum'], 'id,client_ordernum');
                if($omcInfo) {
                    $data['data'][$k]['omc_status'] = 1;
                }
                $orderProcessChangePrice= db("sku_process_price")->where([
                    ['process_stage', '=', '1'],
                    ['sku', '=',$v['sku']],
                ])->value('process_price','0.3');
				$data['data'][$k]['omInfo'] =db('order_material')->where($omWhere)->field($field2)->find();
				$osList=$orderSizeService->getListByOrderId($v['id']);
                if(empty($data['data'][$k]['omInfo'])){
                    $data['data'][$k]['omInfo']=$omInfoData;
                }
                $v['process_price']=empty($v['process_price'])? $orderProcessChangePrice : $v['process_price'] ; //优先取自定义修改的单价 再取款式工价表单价
                $data['data'][$k]['process_price']=!empty($v['process_price']) ? $v['process_price'] : 0.3; //优先取款式工价表单价
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['shicai_count'] = array_sum(array_column($osList, 'shicai_count'));
				$data['data'][$k]['tatal_meter']=round((intval($data['data'][$k]['omInfo']['caichuang_wheat_low_length'])*intval($data['data'][$k]['omInfo']['caichuang_wheat_low']))+(intval($data['data'][$k]['omInfo']['caichuang_wheat_height_length'])*intval($data['data'][$k]['omInfo']['caichuang_wheat_height'])),2);//拉布总米数
                $data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
                $data['data'][$k]['pic'] = $skuService->getInfoBySku($v['sku'],'pic');
                $data['data'][$k]['caichuang_position_txt'] = arrayGet(config('mimo.caichuang_position'), $v['caichuang_position'], '');
            }
            //导出
            if ($export) {
                $this->_exportXls('裁床报表-' .date('YmdHis'), $data['data']);
            }
            $data['count'] = db('order')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
			// 订单进度统计
			if ($page == 1 && $stat=="") {
				$data['stat'] = $cuttingService->getCuttingStat(FACTORY_IDS,$where,$detailWhere);
			}
            return json($data);
        }
        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'stallsKV' => $stallsKV,
            'systemUserKV' => $systemUserKV,
            'caichuangTypeKV' => config('mimo.caichuang_type'),
            'caichuangUserKV' => [0 => '请选择'] + $cuttingService->caichuangUser(),
        ];
        return $this->assign($assign)->fetch();
	}

	/**
	 * 裁床报表导出
	 *
	 * @author 飞燕
	 * @date 2020年9月22日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				date('Y/m/d H:i:s', $v['caichuang_over_time']),
				$v['client_ordernum'],
				$v['sku'],
				$v['caichuang_chuanghao'],
				$v['quantity'],
				$v['shicai_count'],
				$v['tatal_meter'],
				$v['caichuang_type'] == 1 ? '手工裁剪':'电脑裁剪',
				$v['omInfo']['shrink_length'],
				$v['omInfo']['billing_caigou_count'],
				$v['omInfo']['caichuang_shiji_dosage'],
				$v['caichuang_user_name'],
				$v['factory_name'],
				arrayGet(config('mimo.caichuang_position'), $v['caichuang_position'], ''),
				$v['omInfo']['caichuang_t_neadend'],
				$v['omInfo']['caichuang_t_strip'],
                $v['process_price'],
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['裁剪时间','客户订单号','SKU','床号','订单总数','实裁总数','拉布总米数','裁剪类型','缩水后米数','开单采购米数','实际单件用量','裁剪员','工厂','定位','布头','捆条','裁剪单价'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}
	/**
	 * 超量报表导出
	 *
	 * @author 飞燕
	 * @date 2021年1月26日
	 *
	 */
	private function _overfeedXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				$v['is_auto_import_name'],
				$v['factory_name'],
				date('Y/m/d H:i:s', $v['order_time']),
				date('Y/m/d H:i:s', $v['create_time']),
				$v['client_ordernum'],
				$v['sku'],
				$v['mInfo']['name'],
				$v['customer_dosage'],
				$v['material_dosage'],
				$v['overfeed_reason_detail'],
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['账号','工厂','下单时间','创建时间','订单号','sku','面料名称','客户用量','实际用量','超料原因'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}
	/**
	 * 单独同步金鹏扎数
	 *
	 * @author 飞燕
	 * @date 2021年4月23日
	 *
	 */
	public function syncJinpengCut(){
		$orderId      = $this->request->param('order_id/d', 0);
		$mid      = $this->request->param('mid/d', 0);
		$action      = $this->request->param('action/s', 'edit');
		$orderService = new OrderService();
		$orderUserService = new OrderUserService();
		$oInfo = $orderService->getInfoById($orderId);
		$ouEditData = db('order_user')->where('mid',$mid)->select();
    	if (empty($oInfo) ||empty($ouEditData)) {
    		return $this->error('非法访问');
    	}
		if($oInfo['jinpeng_status']!=1){
			return $this->error('此订单尚未同步，禁止扎数单独同步');
		}
		$ouInfo =$orderUserService->getInfoById($mid,'jinpeng_time,jinpeng_status') ;
		if($ouInfo['jinpeng_time']==0) $action="add";
		$res2=$orderService->syncJinpengCut($orderId,'edit',$action,$ouEditData);
		$msgArr=[];
		foreach ($res2['msg'] as $km => $vm) {
			$msgArr[]=$vm;
		}
		$data['code']=1;
		$data['msg']="";
		if($res2){
			if($res2['failNum']==0){
				$data['code']=1;
				$data['msg']="同步成功";
			}elseif ($res2['succeedNum']==0) {
				$data['code']=0;
				$data['msg']="同步失败!<br>".implode('<br>', $msgArr);
			}else{
				$data['code']=0;
				$data['msg']="部分同步失败!<br>".implode('<br>', $msgArr);
			}
		}
		return $this->Json($data['code'], $data['msg']);
	}

	/**
	 * 合裁
	 *
	 * @author 飞燕
	 * @date 2021年4月30日
	 *
	 */
	public function mergeCut(){
		$sku      = $this->request->param('sku/s', '');
		if ($this->request->isAjax()){
			$clientOrdernum      = $this->request->param('client_ordernum/s', '');
			if ($clientOrdernum) {
    			$where[] = ['client_ordernum', 'in', $clientOrdernum];
    		}
            //订单加一级
            order_level($where,'');
			$where[] = ['status', 'in', [0, 1]];
    		$where[] = ['caichuang_can_do', '=', 1];
    		$where[] = ['caichuang_audit_status', 'in', [0, 1]];	// 未审核或部分未审
			$where[]=[
				['sku','=',$sku],
				['caichuang_can_do','=',1],
				['status','in','0,1'],
				['caichuang_audit_status', 'in', [0, 1]],
				['status', 'in', [0, 1]]
			];
			$data['data']=db('order')->where($where)->field("sku,id,client_ordernum,caichuang_can_do")->select();
			$data['code'] = 0;
            $data['msg'] = '';
			return json($data);
		}
		$assign = [
			'sku'=>$sku
    	];
		return $this->assign($assign)->fetch();
	}
	/**
	 * 获取合裁布号信息
	 *
	 * @author 飞燕
	 * @date 2021年4月30日
	 *
	 */
	public function mcSelectMaterial(){
		if ($this->request->isAjax()){
			$sku      = $this->request->param('sku/s', '');
			$orderIds      = $this->request->param('id', []);
			$whereom=[
				['order_id', 'in', $orderIds],
				['caichuang_status','<>',3]
			];
			db('order_material')->where($whereom)->column('mid');
			$where[]=[
				['order_id', 'in', $orderIds],
				['m.type','<>','accessories'],

			];
			$data['data']=db('order_material_item omi')->join('material m', 'omi.material_id = m.id')->where($where)->field("m.name,m.material_sku,m.color,omi.*")->select();
			$data['code'] = 0;
            $data['msg'] = '';
			return json($data);
		}
	}
	/**
	 * 合裁高低层米数信息
	 *
	 * @author 飞燕
	 * @date 2021年5月05日
	 *
	 */
	public function mcOrderMaterial(){
		$ids      = $this->request->param('id', []);
		$where[]=['id','in',$ids];
		$arr=db('order_material_item')->where($where)->column('order_material_id,client_ordernum,material_id,order_id');
		$orderMaterialService = new OrderMaterialService();
		if(empty($arr)) return $this->Json(0,'数据异常');
		try {
			db()->startTrans();

			$post = $this->request->param();
			if(isset($post['id'])) unset($post['id']);
			$post['update_time']=time();

			$mids=array_keys($arr);
			$clientOrdernumStr = implode(",",array_column($arr, 'client_ordernum'));
			$materialId= array_column($arr, 'material_id');//dump($mids);dump($clientOrdernumStr);dump($materialId);exit();
			$orderIds= array_column($arr, 'order_id');
			$whereom[]=['mid','in',$mids];
			$upData = [
				'caichuang_shiji_dosage'=>$post['caichuang_shiji_dosage'],
				'caichuang_strip_dosage'=>$post['caichuang_strip_dosage'],
				'yingcai_count'=>$post['yingcai_count'],
    			'caichuang_status' => 3,
    			'caichuang_audit_time' => time(),
    			'update_time' => time(),
    		];
            $orderService = new OrderService();
            $distributingService = new DistributingService();
			db('order_material')->where($whereom)->update($upData);
			foreach ($orderIds as $key => $value) {
				// 检测面料是否都已审核
				$omList = $orderMaterialService->getListByOrderIdForCutting($value, ['fabric', 'lining']);
				$overNum = 0;
				foreach ($omList as $v) {
					if ($v['caichuang_status'] == 3) $overNum++;
				}
				$caichuangAuditStatus = ($overNum == count($omList)) ? 2 : ($overNum > 0 ? 1: 0);

				// 标记订单裁床审核状态（0未审核，1已部分审核，2已全部审核）
				db('order')->where('id', $value)->update(['caichuang_audit_status' => $caichuangAuditStatus, 'update_time' => time()]);

				//增加辅料配料信息
                $orderInfo = $orderService->getInfoById($value);
                $distributingInfo = $distributingService->getInfoByOrderId($value);
                if (!$distributingInfo) {
                    $distributingData = [
                        'factory_id' => $orderInfo['factory_id'],
                        'order_id' => $value,
                        'client_ordernum' => $orderInfo['client_ordernum'],
                        'is_read' => 0,
                        'status' => 1,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    db('distributing')->insertGetId($distributingData);
                }
            }
			//添加合裁表数据
			$post['caichuang_t_wheat_number']=$post['yingcai_count'];
			unset($post['yingcai_count']);
			$post['material_id']=$materialId[0];
			$post['client_ordernum']=$clientOrdernumStr;
			$post['create_time']=time();
			db('order_merge_cut')->insert($post);
			db()->commit();
			return $this->Json(1, '操作成功');
		} catch (\Exception $e) {
			db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}


	}
	/**
	 * 新增合裁扎数数量
	 *
	 * @author 飞燕
	 * @date 2021年2月22日
	 *
	 * @return string
	 */
	public function addMcZha(){
		$clientOrdernum    = $this->request->param('client_ordernum/s',0);

		$orderMergeCutService = new OrderMergeCutService();
		$orderSizeService=new OrderSizeService();
		$omcInfo=$orderMergeCutService->getInfoByClientOrdernum($clientOrdernum);
		if(!$omcInfo)			return $this->error('非法访问');
		$osList=db('order_size')->where([['client_ordernum','in',$omcInfo['client_ordernum']]])->select();
		$sizeNames= array_unique(array_column($osList, 'size_name'));
		$clientOrdernums=array_unique(array_column($osList, 'client_ordernum'));
		$ouList=db('order_user')->where([['client_ordernum','in',$omcInfo['client_ordernum']]])->select();//dump($ouList);
		$ouList1=$ouList2=[];
		if($ouList) {
			foreach ($ouList as $key => $value) {
				$ouList1[$value['client_ordernum']][]=$value;
			}
			foreach ($ouList1 as $k1 => $v1) {
				$vd=[];
				foreach ($v1 as $k2 => $va2) {
					$vd[$va2['size_name']][]=$va2 ;
				}
				foreach ($vd as $kd => $vvd){
					$ouList2[$k1][$kd]=count($vvd);
				}
			}
		}
    	$assign = [
			'ouData'=>$ouList2,
			'sizeNames'=>$sizeNames,
			'clientOrdernums'=>$clientOrdernums,
			'client_ordernum' => $clientOrdernum,
    	];
		return $this->assign($assign)->fetch();
	}
	/**
	 *
	 *新增合裁扎数详情
	 * @author 飞燕
	 * @date 2021年5月12日
	 *
	 * @return string
	 */
	public function addMcZhaDetail(){
		$zhaNum    = $this->request->param('zha_num',[]);
		$orderService= new OrderService();
		$orderUserService= new OrderUserService();
		$data['data']=[];
		//dump($zhaNum);
		try {
			db()->startTrans();
			foreach ($zhaNum as $ordernum=>$sizeArr){
				$oInfo = $orderService->getInfoByClientOrdernum($ordernum);
				if(empty($oInfo)) return false;
				$upData = [
					'caichuang_chuanghao' => $oInfo['id'],
					'caichuang_user_id' => ADMIN_ID,
					'update_time' => time(),
				];
				db('order')->where('id', $oInfo['id'])->update($upData);
				$lastZha=db('order_user')->where('order_id',$oInfo['id'])->order('zhahao desc')->field('zhahao')->find();
				$zhahao=1;
				if(!empty($lastZha)) {
					$zhahao = arrayGet($lastZha, 'zhahao',0)+1;
				}
				$oInfo = $orderService->getInfoById($oInfo['id']);
				foreach ($sizeArr as $sizeName => $newZhaCount) {
					$zhaCountShiji = db('order_user')->where("order_id = {$oInfo['id']} and size_name = '{$sizeName}'")->count('mid');
					//新增扎号
					$zhaCount=$newZhaCount-$zhaCountShiji;
					for ($x=1;$x<=$zhaCount; $x++){
						$orderUserData = [
							'factory_id' => $oInfo['factory_id'],
							'user_id' => ADMIN_ID,
							'chuanghao' => $oInfo['caichuang_chuanghao'],
							'zhahao' => $zhahao,
							'size_name' => $sizeName,
							'order_id' => $oInfo['id'],
							'client_ordernum' => $oInfo['client_ordernum'],
							'create_time' => time(),
						];
						db('order_user')->insert($orderUserData);
						$zhahao++;
					}
					//删除扎号
//					$delzhaCount=$zhaCountShiji-$newZhaCount;dump($zhaCountShiji);dump($newZhaCount);dump($delzhaCount);//exit();
//					for ($d=1;$x<=$delzhaCount; $d++){
//						$delInfo=db('order_user')->where('order_id',$oInfo['id'])->order('zhahao desc')->find();
//						$delZhahao = arrayGet($delInfo, 'zhahao',0);
//						db('order_user')->where("order_id = {$oInfo['id']} and zhahao = {$delZhahao}")->delete();dump([$delInfo]);//exit();
//						$orderService->syncJinpengCut($oInfo['id'],"edit","dele",[$delInfo]);
//					}
				}
				$ouList=db('order_user')->where([['client_ordernum','=',$ordernum]])->select();
				$data['data'] = array_merge($ouList, $data['data']);
			}
			db()->commit();
			return $this->Json(1, '修改成功',$data['data']);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}
	//删除全部扎号
	public function delMcZhaDetail(){
		$zhaNum    = $this->request->param('zha_num',[]);
		$orderService= new OrderService();
		$orderUserService= new OrderUserService();
		$data['data']=[];
		//dump($zhaNum);
		try {
			db()->startTrans();
			foreach ($zhaNum as $ordernum=>$sizeArr){
				db('order_user')->where("client_ordernum = '{$ordernum}'")->delete();
			}
			db()->commit();
			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 *
	 *保存合裁扎数并同步至金鹏
	 * @author 飞燕
	 * @date 2021年5月12日
	 *
	 * @return string
	 */
	public function editMcStrit(){
		$jianshuArr    = $this->request->param('jianshu',[]);
		$allJianCount    = $this->request->param('allJianCount/n',0);
		$allZhaCount    = $this->request->param('allZhaCount/n',0);
		$action    = $this->request->param('action/s','add');
		$orderUserService= new OrderUserService();
		$orderService= new OrderService();
		$orderMaterialService= new OrderMaterialService();
		$shiJianCount= array_sum($jianshuArr);
		$shiZhaCount = count($jianshuArr);
		if($action=="add"){
			if($shiJianCount!=$allJianCount || $shiZhaCount!=$allZhaCount ){
				return $this->Json(0, '总扎数或者总件数不一致',[$shiJianCount,$allJianCount,$shiZhaCount,$allZhaCount]);
			}
		}
		try {
			db()->startTrans();
			$orderIdArr=[];
			foreach ($jianshuArr as $mid => $jianshu) {
				$result=db('order_user')->where('mid',$mid)->update(['jianshu'=>$jianshu,'update_time'=>time()]);
				$orderId=db('order_user')->where('mid',$mid)->field('order_id')->find();
				$orderIdArr[]= arrayGet($orderId, 'order_id');
			}
			$orderIdArr = !empty($orderIdArr)?array_unique($orderIdArr):[];
			foreach ($orderIdArr as $key => $value) {
				$oInfo=$orderService->getInfoById($value);
				$where=[
					['client_ordernum','like',"%".$oInfo['client_ordernum']."%"],
				];
				$omcInfo=db('order_merge_cut')->where($where)->findOrEmpty();
				$materialId=$omcInfo['material_id'];
				$omData=[
					'caichuang_status'=>3,
					'caichuang_audit_time'=>time(),
					'caichuang_over_time'=>time(),
					'caichuang_pull_time'=>time()
				];
				$where=[
					'material_id'=>$materialId,
					'order_id'=>$value
				];
				db('order_material')->where($where)->update($omData);
				//同时更新order表 start
//				$omcList=$orderMaterialService->getListByOrderIdForCutting($value);
//
//				foreach ($omcList as $komc => $vomc) {
//					if($vomc['caichuang_status']!=3) $can=1;
//				}
//				if(!isset($can)) {
					$oData=[
						'caichuang_audit_status'=>1,
						'caichuang_status'=>1,
						'caichuang_user_id'=>ADMIN_ID,
						'caichuang_over_time'=>time()
					];
					db('order')->where('id',$value)->update($oData);
				//}
				//同时更新order表 end
				//同步金鹏订单
				if(env('jinpeng_api_status')==1 && ($oInfo['jinpeng_status']!=1 || $action=="dele")){
					$res1=$orderService->syncJinpengOrder($value,$action);
					$msgArr[]=$res1['msg'];
				}
				//同步金鹏订单裁剪扎数
				if(env('jinpeng_api_status')==1 && $action!="dele"){
					$res2=$orderService->syncJinpengCut($value,$action,$action);
					foreach ($res2['msg'] as $km => $vm) {
						$msgArr[]=$vm;
					}
				}
			}

			db()->commit();
			return $this->Json(1, '保存成功');
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}
	/**
	 *
	 *合裁扎数打印
	 * @author 飞燕
	 * @date 2021年5月14日
	 *
	 * @return string
	 */
	public function omcPrint(){
		$clientOrdernum    = $this->request->param('client_ordernum/s','');
		$omcInfo = [];
		$ouList = [];
		$osList = [];
    	if ($clientOrdernum != '') {
    		$orderService = new OrderService();
    		$skuService = new SkuService();
    		$orderSizeService = new OrderSizeService();
    		$orderMaterialService = new OrderMaterialService();

    		$oInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    		if (!$oInfo) {
    			$error = "未找到订单信息";
    		} elseif($oInfo && $oInfo['caichuang_audit_status']==0 && $oInfo['caichuang_status'] == 0) {
    			$error = "该订单还未进行裁剪审核";
			} else {
    			$orderId = $oInfo['id'];
    			//$clientOrdernum = $oInfo['client_ordernum'];
				$where=[
					['client_ordernum','like',"%".$clientOrdernum."%"],
				];
				$omcInfo=db('order_merge_cut')->where($where)->findOrEmpty();
				if($omcInfo){
					$clientOrdernumArr= explode(',', $omcInfo['client_ordernum']);
					$ouList1=db('order_user')->where([['client_ordernum','in',$clientOrdernumArr]])->order('client_ordernum asc,zhahao asc')->select();
					$caichaungRemarkKV=db('order')->where([['client_ordernum','in',$clientOrdernumArr],['status','not in',99]])->column("id,caichuang_remark");
					foreach ($ouList1 as $key => $value) {
						$ouList[$value['order_id']][]=$value;
						//$ouList[$value['order_id']][1] = arrayGet($caichaungRemarkKV, $value['order_id'],'');
					}
					$osList1=db('order_size')->where([['client_ordernum','in',$clientOrdernumArr]])->select();
					foreach ($osList1 as $kos => $vos) {
						$osList[$vos['client_ordernum']][0][]=$vos;
						$osList[$vos['client_ordernum']][1] = arrayGet($caichaungRemarkKV, $vos['order_id'],'');
					}
				}
			}
		}

		$assign = [
    		'clientOrdernum' => $clientOrdernum,
			'omcInfo'=>$omcInfo,
			'ouList'=>$ouList,
			'osList'=>$osList
    	];
    	return $this->assign($assign)->fetch();
	}
	/**
	 *
	 *单独删除合裁扎数
	 * @author 飞燕
	 * @date 2021年5月12日
	 *
	 * @return string
	 */
	public function delMcZha(){
		$mid    = $this->request->param('mid',0);
		$orderUserService=new OrderUserService();
		$orderService=new OrderService();
		$info=$orderUserService->getInfoById($mid);
		if(!$info)			return $this->error("数据错误");
		try {
			db()->startTrans();
			$result=db('order_user')->where('mid',$mid)->delete();
			if($result){
				$res2=$orderService->syncJinpengCut($info['order_id'],"edit","dele",[$info]);//同步删除金鹏
			}
			db()->commit();
			return $this->Json(1, '操作成功');
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}
	/**
	 *
	 *单独编辑合裁扎数
	 * @author 飞燕
	 * @date 2021年5月12日
	 *
	 * @return string
	 */
	public function singeEditMcZha(){
		$mid    = $this->request->param('mid',0);
		$jianshu    = $this->request->param('jianshu',0);
		$orderUserService=new OrderUserService();
		$orderSizeService=new OrderSizeService();
		$orderService=new OrderService();
		$info=$orderUserService->getInfoById($mid);
		if(!$info)			return $this->error("数据错误");
		try {
			db()->startTrans();
			$result=db('order_user')->where('mid',$mid)->update(['jianshu'=>$jianshu,'jinpeng_status'=>0,'update_time'=> time()]);
			$where=[
				'order_id'=>$info['order_id'],
				'size_name'=>$info['size_name']
			];
			$shicaiCount=db('order_user')->where($where)->sum("jianshu");
			$osData['shicai_count']=$shicaiCount;
			$orderSizeService->updateInfo($osData, $where);
			db()->commit();
			return $this->Json(1, '操作成功');
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	public function dosageEdit(){
		$clientOrdernum = $this->request->param('client_ordernum/s', '');
		$orderMergeCutService=new OrderMergeCutService();
		$orderMaterialService=new OrderMaterialService();
		$omcInfo=$orderMergeCutService->getInfoByClientOrdernum($clientOrdernum);
		if(!$omcInfo) return $this->error ("数据异常");
		if ($this->request->isPost()) {
			$postData=$this->request->post();
			$clientOrdernums= explode(',', arrayGet($omcInfo, 'client_ordernum',''));
			$materialId=arrayGet($omcInfo, 'material_id',0);
			$upData = [
				'caichuang_shiji_dosage'=>arrayGet($postData, 'caichuang_shiji_dosage',0),
				'caichuang_strip_dosage'=>arrayGet($postData, 'caichuang_strip_dosage',0),
				'yingcai_count'=>arrayGet($postData, 'caichuang_t_wheat_number',0),
    			'update_time' => time(),
    		];
			$where=[
				['client_ordernum','in',$clientOrdernums],
				['material_id','=',$materialId]
				];
			db('order_material')->where($where)->update($upData);
			$result=db('order_merge_cut')->update($postData);
			if($result){
				return $this->Json(1);
			}else{
				return $this->Json(0);
			}
		}

		$assign = [
			'clientOrdernum'=>$clientOrdernum,
			'omcInfo'=>$omcInfo
		];
		return $this->assign($assign)->fetch();
	}

    /**
     * 切片打包外发打标
     * @date 2021/11/23
     * @author zhuguosen 905502314@qq.com
     */
    public function cutPackageLabelV2()
    {
        $orderId = $this->request->param('order_id/d', 0);
        $action = $this->request->param('action');
        $where[] = ['o.id', '=', $orderId];
        $orderInfo = db('order o')
            ->field('o.factory_id,f.type,o.group_id,oot.group_id as outgo_group_id,o.client_ordernum
            ,oot.cut_packages,oot.cut_packages_remark
            ,g.address as group_address,g.mobile as group_mobile,g.name as group_name_source
            ')
            ->join('order_outgo oot', 'o.id = oot.order_id', 'left')
            ->join('factory f', 'o.factory_id = f.id', 'left')
            ->join('group g', 'g.id = oot.group_id', 'left')
            ->where($where)->find();
        $factoryKV = getFactoryKV(false);
        $orderInfo['factory_name'] = isset($factoryKV[$orderInfo['factory_id']]) ? $factoryKV[$orderInfo['factory_id']] : '未分配';
        if ($orderInfo['type'] === 1) {
            $orderInfo['group_name'] = '';
            $orderInfo['factory_outgo_name'] = $orderInfo['group_name_source'];
        } else {
            $orderInfo['group_name'] = $orderInfo['group_name_source'];
            $orderInfo['factory_outgo_name'] = '';
        }
        if (empty($action)) {
            return $this->Json(1, '', $orderInfo);
        }
        //2,打标信息显示
        //2.1 参数处理
        $cut_packages = $this->request->param('cut_packages/d', 0);
        $cut_packages_remark = $this->request->param('cut_packages_remark/s');
        if ($cut_packages <= 0) {
            echo "<script>alert('打标包数必须大于0，请返回确认');window.close();</script>";
            return true;
        }
        //3,数据表修改
        $res = (new \app\common\service\OrderOutgo())->cutPackageLabel($orderId, $cut_packages, $cut_packages_remark);
        //4,信息显示
        $list = db("order_outgo_cpl ooc")
            ->field('ooc.*,o.client_ordernum
            ,f.name as factory_name,f.type
            ,g.name as group_name,g.mobile,g.address
            ,oot.cut_packages_remark')
            ->join('wx_order o ', 'o.id=ooc.order_id', 'left')
            ->join('wx_factory f', 'f.id=o.factory_id', 'left')
            ->join('wx_order_outgo oot', 'oot.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where([['ooc.order_id', '=', $orderId]])->select();
        foreach ($list as $k => $v) {
            $qrCode = new QrCode("cutPackageLabel-{$v['client_ordernum']}-{$v['num_0']}-{$v['num_1']}");
            $list[$k]['qrcode'] = $qrCode->writeDataUri();
        }
        $this->assign('list', $list);
        return $this->fetch();
    }
}